Deserializing a JSON into a JavaScript object Deserializing a JSON into a JavaScript object json json

Deserializing a JSON into a JavaScript object


Modern browsers support JSON.parse().

var arr_from_json = JSON.parse( json_string );

In browsers that don't, you can include the json2 library.


The whole point of JSON is that JSON strings can be converted to native objects without doing anything. Check this link

You can use either eval(string) or JSON.parse(string).

However, eval is risky. From json.org:

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.


Do like jQuery does! (the essence)

function parseJSON(data) {    return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); }// testingobj = parseJSON('{"name":"John"}');alert(obj.name);

This way you don't need any external library and it still works on old browsers.