JSON Objects

JSON Objects

JSON objects are written strictly inside curly braces {}.

Similar to JavaScript objects, they hold multiple name/value pairs separated by commas.


Accessing Object Values

Once you parse a JSON string into a JavaScript variable, it behaves like a normal object.

You can access the values inside it using simple dot notation (obj.key).

Alternatively, you can access values using bracket notation (obj["key"]), which is useful for dynamic keys!


Looping Through an Object

If your object contains dozens of keys, you can loop through it instantly.

You use the for...in loop to iterate through all properties within a JSON object.

This is extremely helpful when rendering unknown API payloads to the HTML screen.

JSON Object Loop Example:

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

let text = ""; // Looping through the parsed object keys for (const x in myObj) { text += x + ": " + myObj[x] + "\n"; } console.log(text);


Nested JSON Objects

Values in a JSON object can be another massive JSON object!

You can access these nested objects by chaining dot notation: user.address.zipcode.


Exercise 1 of 1

?

Which type of loop is specifically designed to iterate over the keys of an Object?