Back to Blog Home

How to Parse Json in Javascript

Nishant Verma| Javascript | 6 months, 1 week



 

Json is one of the most widely used data format to transfer data from server to client side. When the Json data is transferred, it is converted into a string for easy transportation. Now to work with the json data in your client side using javascript, you need to convert the json data into a javascript object or in other words you need to parse data in javascript. 

 

To parse the data we use a javascript method called JSON.parse(). JSON.parse() method in javascript, parses a json string and returns a javascript object.

 

Syntax for JSON.parse() looks something like this :

 

JSON.parse(string, function)

 

where string is the required parameter which is a string in json format which needs to be parsed. function is an optional paramter which is a function used to transform the result. The function is called for each item. Any nested objects are transformed before the parent. 

 

For example, if we recieve this json data from the server in the string format :

 

'{ "company":"apple", "founder":"steve jobs", "product":"iphone"}'

 

We will have to parse the string to convert it into a javascript object to access the key values. We will use the JSON.parse() method :

 

var obj = JSON.parse('{ "company":"apple", "founder":"steve jobs", "product":"iphone"}')

 

Now json string is converted into a javascript object obj, we can access the key values like :

 

alert(obj.company)

 

Output :

 

apple

 



Join 1000+ People Who Subscribe to Weekly Blog Updates

Back to Blog Home