Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JSON Objects

This is a string in JSON format:

‘{“name”:”John”, “age”:30, “car”:null}’

The JSON string contains a JSON object literal:

{“name”:“John”“age”:30“car”:null}

JSON object literals are enclosed in curly braces {}.

They consist of key/value pairs, where keys and values are separated by a colon.

Keys must be strings, and values must be a valid JSON data type, which can be:

  • string
  • number
  • object
  • array
  • boolean
  • null

Each key/value pair is separated by a comma.

A common mistake is referring to a JSON object literal as “a JSON object.”

JSON itself cannot be an object; it is a string format.

The data is only considered JSON when it is in string format. Once converted to a JavaScript variable, it becomes a JavaScript object.

JavaScript Objects

You can create a JavaScript object from a JSON string literal.

Example

myObj = {“name”:“John”“age”:30“car”:null};

Typically, you create a JavaScript object by parsing a JSON string.

Example

myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’;
myObj = JSON.parse(myJSON);

Accessing Object Values

You can access the values of an object using dot (.) notation.

Example

const myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’;
const myObj = JSON.parse(myJSON);
x = myObj.name;

You can also access object values using bracket ([]) notation.

Example

const myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’;
const myObj = JSON.parse(myJSON);
x = myObj[“name”];

Looping an Object

You can iterate through object properties using a for-in loop.

Example

const myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’;
const myObj = JSON.parse(myJSON);

let text = “”;
for (const x in myObj) {
  text += x + “, “;
}

In a for-in loop, use bracket notation to access the values of the properties.

Example

const myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’;
const myObj = JSON.parse(myJSON);

let text = “”;
for (const x in myObj) {
  text += myObj[x] + “, “;
}