Menu

7 Dec 2014

JSON (Javascript Object Notation) is a popular data format on web now-a-days. Since, its easier for both humans and computers to read and process it, most web-applications support JSON as input format.
In this tutorial, we will learn how to extract useful data from JSON i.e. parsing a JSON using JavaScript since JavaScript is used for processing in web applications and websites. We will take different formats of JSON as input and parse them accordingly. Most important things is we always parse a JSON using the keys of the Data we want to extract.
Sample JSON "Key-Value" format :

{
Key1 : "value1",
Key2 : "value2",
Key3 : "value3",
and so on ....
}

Now suppose you have a JSON text in javascript variable and you wish to convert it into a Javascript object as JSON, you can use simply JSON.parse() function. It converts JSON text to JSON object.
A small example for you :

Now we, can access ID and Name the same we learnt before and to parse Info part of JSON, we ways are there :

//Suppose above JSON is stored in a Javascript variable data
var birth=data['info']['Birth'];//same way which we used earlier
Or by using a dot operator the following way :
var site=data.info['Website'];//data dot info will help us get to next level of braces curly {}

In above type of JSON, we have to parse info list (a list is surrounded by stapler brackets [] ) :

var info=data.info;
Now we can extract information from each map (a map is surrounded by curly brackes {}) :
var info=data.info;
var birthInfo=info[0];//accessing first map of info list
var birth=birthInfo['Birth'];//or directly we can write info[0]['Birth']

So these are the ways we can parse a JSON in JavaScript easily.
Hope you might have understood and got clarity with this topic, if have some doubts and queries feel free to put your thoughts in comments.