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:
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. |
You can create a JavaScript object from a JSON string literal.
myObj = {“name”:“John”, “age”:30, “car”:null}; |
Typically, you create a JavaScript object by parsing a JSON string.
myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’; myObj = JSON.parse(myJSON); |
You can access the values of an object using dot (.) notation.
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.
const myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’; const myObj = JSON.parse(myJSON); x = myObj[“name”]; |
You can iterate through object properties using a for-in loop.
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.
const myJSON = ‘{“name”:”John”, “age”:30, “car”:null}’; const myObj = JSON.parse(myJSON); let text = “”; for (const x in myObj) { text += myObj[x] + “, “; } |