Deserializing JSON to JavaScript objects
The simplest of all cases is reading JSON data into JavaScript objects. Data formatted in this way is of lightweight and additionally it is a subset of JavaScript. There are several ways to read this data and we will take a look at how this can be done by creating a simple JSON snippet and then converting it to JavaScript objects.
How to do it...
This example will be simple enough to be a script in an HTML file or even executed on a firebug or developer tools console:
We first need the following serialized JSON string:
var someJSONString = '{"comment":"JSON data usually is retrieved from server","who":"you"}';
There are few different ways to do this without adding external JavaScript dependency, one is through the use of
eval
, the other is through the use ofjson
:var evalData = eval('(' + someJSONString + ')'); var jsonData = JSON.parse(someJSONString);
After this we will try to access some of the attributes form the deserialized object:
...