views:

225

answers:

1

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...

+3  A: 

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".

Nick Spacek
@nick that worked .. Because i use jquery only...
Pandiya Chendur
@nick which is faster...
Pandiya Chendur
You should include brackets inside the eval parentheses: `eval('({"name":"John"})');` If you want raw speed, `var obj = new Function('return {"name":"John"}')` will be quickest. Be aware however, that jQuery.parseJSON checks the JSON to ensure it is valid JSON; and not malicious code. Both the `new Function` and the `eval` methods do not. I would recommend jQuery.parseJSON.
Matt
Are you expecting a really big string of JSON? If speed really is a concern (ie. you are expecting a large JSON string and need to perform well on really slow machines, or something similar) and you are the one controlling the JSON string, there's no reason to be afraid of using eval or the Function syntax Matt mentioned (if you are 100% sure that the JSON string will always be valid JSON and nothing malicious). However, it might (maybe) be harder to find syntax errors in the JSON using those methods.
Nick Spacek