JSON Literals

This is a JSON string

JavaScript Objects

You can create a JavaScript object from a JSON object literal:

Example

myObj = {"name":"John", "age":30, "car":null};

Normally, 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 object values by 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 by 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 loop through object properties with 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 the bracket notation to access the property values:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

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