JSON Object Literals
This is a JSON string:
'{"name":"John", "age":30, "car":null}'
Inside the JSON string is a JSON object literal:
{"name":"John", "age":30, "car":null}
JSON Object Literals
- Surrounded by curly braces {}.
- Contain key/value pairs.
- Keys and values are separated by a colon.
- Keys must be strings, and values must be a valid JSON data type: string, number, object, array, boolean, null.
- Each key/value pair is separated by a comma.
It is a common mistake to call a JSON object literal "a JSON object." JSON is a string format. When converted to a JavaScript variable, it becomes a JavaScript object.
JavaScript Objects
You can create a JavaScript object from a JSON object literal:
const myObj = {"name": "John", "age": 30, "car": null};
Normally, you create a JavaScript object by parsing a JSON string:
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
Accessing Object Values
Using dot notation:
const x = myObj.name;
Using bracket notation:
const x = myObj["name"];
Looping Through an Object
You can loop through object properties with a for-in loop:
let text = "";
for (const key in myObj) {
text += key + ", ";
}
In a for-in loop, use bracket notation to access property values:
let text = "";
for (const key in myObj) {
text += myObj[key] + ", ";
}