JSON

JSON Object

JSON Object

Now that we know what JSON objects are, let us create simple to complex JSON objects. Before we begin, let us clarify one common misconception. A JSON object literal is not a JSON object. JSON is a string format and thus cannot be an object. The data is present in JSON in a string format but it becomes object once it is converted to a JavaScript variable.

Now we create JSON objects using JavaScript. The below statement creates an empty object.

var myJSONObj = {};

The below line creates a new Object.

var JSONObj = new Object();

The following line creates an object with attribute name with value in string, attribute brand with value in string, attribute class with value in string and attribute price with integer value. 

var myJSONCarObj = { "name": "Creta", "brand": "Hyundai", "color": "red", price":500 };

Please note that an attribute is accessed by using '.' operator. For e.g. myJSONCarObj.color is used to access color property. The below line shows how to parse a JSON string and create a JavaScript object from it.

myJSONCar = '{ "name": "Creta", "brand": "Hyundai", "color": "red", price":500 }';
myCarObj = JSON.Parse(myJSONCar);
Now you can access any property using array subscript indexing. For e.g
Price = myCarObj[“price”];