JSON Objects

JSON objects is written in key/value pairs. JSON objects are surrounded by curly braces {}. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon (:). Each key/value pair is separated by a comma.

{ "key1": "value1", "key2", "value2" }.

var jsonObj = { "name":"David", "age":32, "city": "California" };

Accessing Object Values
You can access the object values by using dot (.) notation:

jsonObj = { "name":"David", "age":32, "city": "California" };
x = jsonObj.name; //returns "David"

You can also access the object values by using bracket ([]) notation:

var jsonObj = { "name":"David", "age":32, "city": "California" };
x = jsonObj["name"];

Looping an Object
You can loop through the object properties by using the for-in loop.

var jsonObj = { "name":"David", "age":32, "city": "California" };

for (x in jsonObj) {
console.log(x + '\n');

In a for-in loop, use the bracket notation to access the property values:

jsonObj = { "name":"David", "age":32, "city": "California" };

for (x in jsonObj) {
console.log(jsonObj[x] + '\n');

Nested JSON Objects
Values in a JSON object can be another JSON object.

var jsonObj = {
"favourites": {

You can access nested JSON objects by using the dot notation or bracket notation:

x = jsonObj.favourites.favourite3;
x = jsonObj.favourites["favourite3"];

Modify Values
You can use the dot notation to modify any value in a JSON object.

jsonObj.favourites.favourite3 = "Cricket";

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

jsonObj.favourites["favourite3"] = "Cricket";

Delete Object Properties
Use the delete keyword to delete properties from a JSON object.

delete jsonObj.favourite.favourite3;
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +