Json Structure

Java Script Object Notation (JSON) is one of the most popular and commonly used way to represent information. This post explains simple & complex constructions of JSON message structures.

Let’s take an example of a Car. Information about a Car can be represented in Json format as follows:

var car = {
       "name"  : "Audi",
       "model" : "2010",
       "cost"  : "30000"
};

Above representation is derived from Javascript. Here we have created a variable ‘car’ whose value is an object enclosed within curly braces. This object contains "name":"value" pairs, separated by comma.

To access the object property, we can simply use object.property notation:

car.name                     //produces "Audi"
car.model                    //produces "2010"

Now the object can be complex. For instance, below is an example of nested objects

var car = {
       "name"  : "Audi",
       "model" : "2010",
       "cost"  : "30000",
       "engine": {
          "type" : "diesel",
          "power" : "88KW 2.0TDI"
       }
};

To access the object properties:

car.name                     //produces "Audi"
car.engine.type              //produces "diesel"

JSON does support collection representations. For instance, below is an example of storing JSON in Arrays

var carFleet = [
 {
       "name"  : "Audi",
       "model" : "2010",
       "cost"  : "30000",
       "engine": {
          "type" : "diesel",
          "power" : "88KW 2.0TDI"
       }
},
 {
       "name"  : "Jaguar",
       "model" : "2012",
       "cost"  : "70000",
       "engine": {
          "type" : "diesel",
          "power" : "140KW 3.0TDI"
       }
}
];

In order to access the object properties, use [] (index starts with 0):

carFleet[0].name              //produces "Audi"
carFleet[1].engine.power      //produces "140KW 3.0TDI"

Even more complex information can be represented using JSON:

var carFleet = [
    {
        "name": "Audi",
        "model": "2010",
        "cost": "30000",
        "engine": {
            "type": "diesel",
            "power": "88KW 2.0TDI"
        },
        "colors": [
            "Black",
            "Red",
            "White"
        ]
    },
    {
        "name": "Jaguar",
        "model": "2012",
        "cost": "70000",
        "engine": {
            "type": "diesel",
            "power": "140KW 3.0TDI"
        },
        "colors": [
            "Gray",
            "Black",
            "White"
        ]
    }
];

Again, we can access the individual value using object.property notation, in conjunction with [] for arrays.

carFleet[0].name              //produces "Audi"
carFleet[1].engine.power      //produces "140KW 3.0TDI"
carFleet[1].colors[2]         //produces "White"

TIP:

You can validate the correctness of your JSON on http://jsonlint.com/

That’s it. In the next post we will learn about how to use JSON in your projects.

References