JSON Object
- Previous Page JSON Serialization
- Next Page JSON Array
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;
You can also use square brackets ([]
)to access the object value:
Example
myObj = { "name":"Bill Gates", "age":62, "car":null }; x = myObj["name"];
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; }
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]}; }
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"];
Modify Value
You can use a dot to modify any value in a JSON object:
Example
myObj.cars.car3 = "Mercedes Benz";
You can also use parentheses to modify the value in a JSON object:
Example
myObj.cars["car3"] = "Mercedes Benz";
Delete Object Property
Use delete
Use keywords to delete the properties of a JSON object:
Example
delete myObj.cars.car1;
- Previous Page JSON Serialization
- Next Page JSON Array