JSON or JavaScript Object Notation is a very lightweight data-interchange format. It’s also language independent and easy to understand. In this article, we will look into How to Parse JSON string in JavaScript using JSON.parse() method.
How to Parse JSON string in JavaScript using Json.parse()?
Syntax
JSON.parse(text[, reviver])
Parameters
text :-
The string to parse as JSON. See the JSON
object for a description of JSON syntax.
reviver :-
Optional If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Return Value
Returns the object corresponding to the JSON text which is passed as a parameter
Examples of Parsing Simple JSON string in JavaScript and it’s output
JSON.parse('{}'); // {} JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null
Complex JSON String Example:
var text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj = JSON.parse(text); console.write(obj); //output :- // Object {employees: Array[3]}
Console Window Output of JSON.Parse()
Browser Support:
Most of the modern browsers support JSON.Parse() method which is defined in ECMA Script-262 5th Edition. According to Mozilla Developer Network below are the browsers that support JSON.Parse().
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | 3.5 (1.9.1) | 8.0 | 10.5 | 4.0 |
Mobile
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 1.0 (1.0) | (Yes) | (Yes) | (Yes) |
Older Browser Workaround
There is a workaround for the older browser versions. You could implement the same functionality using json2.js. The other option is to use eval() method to parse the JSON string into JavaScript object.
Example of eval() method to Parse JSON string
var strJSON = '{"result":true,"count":1}'; var objJSON = eval("(function(){return " + strJSON + ";})()"); console.log(objJSON.result); //true console.log(objJSON.count); //1