ACP
ACP

Reputation: 35268

What is the most efficient way to parse json in jquery?

I am using json data and iterating it through jquery and displaying my results...

Using var jsonObj = JSON.parse(HfJsonValue); works in firefox but not in IE6....

HfjsonValue is a json string which is returned from my aspx code behind page... SO i dont use ajax... Any suggestion to get my json parsed better and cross browser one...

Upvotes: 0

Views: 4570

Answers (1)

Nick Spacek
Nick Spacek

Reputation: 4773

Probably this: http://api.jquery.com/jQuery.parseJSON/

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

...uh of course, that's only if you want to use jQuery 1.4. :) I think that the JSON built-in functionality is a fairly new addition to the browsers that actually try to implement standards.

Edit

Just as a follow up, you can turn a JSON string into a JavaScript object by calling the "eval" function on it:

var obj = eval('({"name":"John"})');
alert( obj.name === "John" );

That should give the same result as the jQuery parseJSON above. The difference is that the JavaScript "eval" function will run whatever code is inside, so if the source of your JSON is an external site or another untrusted source, that source could inject malicious code into the string you are expecting to only contain JSON.

I believe that there is a new recommendation that browsers implement built-in JSON parsing, which would enforce the JavaScript object literal format on the string, which would provide a safe alternative to "eval".

Edit 2

Having never actually used eval to process JSON, I incorrectly assumed my example would work. It's fixed now with the addition of the surrounding braces.

Upvotes: 6

Related Questions