JSON Object

Object syntax

Example

{ "name":"Bill Gates", "age":62, "car":null }

JSON objects are enclosed by curly braces {} Enclosed.

JSON objects are written as key/value pairs.

Keys must be strings, and values must be valid JSON data types (string, number, object, array, boolean, or null).

Keys and values are separated by a colon.

Each key/value pair is separated by a comma.

Access object value

You can access the object value by using.)to access the object value:

Example

myObj =  { "name":"Bill Gates", "age":62, "car":null };
x = myObj.name;

Try It Yourself

You can also use square brackets ([])to access the object value:

Example

myObj =  { "name":"Bill Gates", "age":62, "car":null };
x = myObj["name"];

Try It Yourself

To iterate over an object

You can use for-in To iterate over object properties:

Example

myObj =  { "name":"Bill Gates", "age":62, "car":null };
for (x in myObj) {
   document.getElementById("demo").innerHTML += x;
}

Try It Yourself

In the for-in loop, useBracket notationTo access the property value:

Example

myObj =  { "name":"Bill Gates", "age":62, "car":null };
for (x in myObj) {
   document.getElementById("demo").innerHTML += myObj[x]};
}

Try It Yourself

Nested JSON Object

A value in a JSON object can be another JSON object.

Example

myObj =  {
   "name":"Bill Gates",
   "age":62,
   "cars": {
	  "car1":"Porsche",
	  "car2":"BMW",
	  "car3":"Volvo"
   }
}

You can access nested JSON objects using dots and parentheses:

Example

x = myObj.cars.car2;
//or:
x = myObj.cars["car2"];

Try It Yourself

Modify Value

You can use a dot to modify any value in a JSON object:

Example

myObj.cars.car3 = "Mercedes Benz";

Try It Yourself

You can also use parentheses to modify the value in a JSON object:

Example

myObj.cars["car3"] = "Mercedes Benz";

Try It Yourself

Delete Object Property

Use delete Use keywords to delete the properties of a JSON object:

Example

delete myObj.cars.car1;

Try It Yourself