Accessing JSON Data

Course- Javascript >

To recover the data encoded into the JSON string, you need to somehow convert the string back to JavaScript code. This is usually referred to as deserializing the string.

Using eval()

Only more recent browsers have native support for JSON syntax (we talk about using native browser support in just a moment). However, since JSON syntax is a subset of JavaScript, the JavaScript function eval() can be used to convert a JSON string into a JavaScript object.

Note:

The JavaScript eval() function evaluates or executes whatever is passed as an argument. If the argument is an expression, eval() evaluates the expression; for example,

var x = eval(4 * 3); // x=12

If the argument comprises one or more JavaScript statements, eval() executes those statements:

eval("a=1; b=2; document.write(a+b);"); // writes 3 to the page

The eval() function uses the JavaScript interpreter to parse the JSON text and produce a JavaScript object:

var myObject = eval ('(' + jsonObjectString + ')');

You can then use the JavaScript object in your script:

var user = '{"username" : "philb1234","location" : "Spain","height" :
1.80}';
var myObject = eval ('(' + user + ')');
alert(myObject.username);                    
                    

Using Native Browser Support

All recent browsers offer native support for JSON, making the use of eval() unnecessary.

  • Firefox (Mozilla) 3.5+
  • Internet Explorer 8+
  • Google Chrome
  • Opera 10+
  • Safari 4+

Browsers with native JSON support create a JavaScript object called JSON to manage JSON encoding and decoding. The JSON object has two methods, stringify() and parse().

JSON.parse()

You can interpret a JSON string using the method JSON.parse(), which takes a string containing a JSON-serialized object and breaks it up, creating an object with properties corresponding to the "parameter":"value" pairs found in the string:

var Mary = '{ "height":1.9, "age":36, "eyeColor":"brown" }';
var myObject = JSON.parse(Mary);
var out = "";
for (i in myObject) {
out += i + " = " + myObject[i] + "\n";
} alert(out);                    
                    
Using JSON.parse()