Saturday, 1 February 2014

How to parse JSON in JavaScript

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj
= JSON.parse(json);

alert
(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj
= JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More