简体   繁体   English

在jquery中解析json的最有效方法是什么?

[英]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... 我正在使用json数据并通过jquery进行迭代并显示我的结果...

Using var jsonObj = JSON.parse(HfJsonValue); 使用var jsonObj = JSON.parse(HfJsonValue); works in firefox but not in IE6 .... firefox有效,但在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... HfjsonValue是一个json字符串,它是从aspx code behind page我的aspx code behind page返回的...所以我不使用ajax ...关于更好地解析json并跨浏览器的任何建议...

Probably this: http://api.jquery.com/jQuery.parseJSON/ 可能是这样的: 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. ...嗯,当然,仅当您想使用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. :)我认为JSON内置功能是对实际上尝试实现标准的浏览器的相当新的补充。

Edit 编辑

Just as a follow up, you can turn a JSON string into a JavaScript object by calling the "eval" function on it: 作为后续操作,您可以通过在其上调用“ eval”函数将JSON字符串转换为JavaScript对象:

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

That should give the same result as the jQuery parseJSON above. 那应该得到与上面的jQuery parseJSON相同的结果。 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. 区别在于JavaScript“ eval”函数将运行内部的任何代码,因此,如果JSON的源是外部站点或其他不受信任的源,则该源可能会将恶意代码注入到您期望仅包含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". 我相信,有一个新的建议,即浏览器应实现内置的JSON解析,该解析将对字符串强制执行JavaScript对象文字格式,这将为“ eval”提供一种安全的替代方法。

Edit 2 编辑2

Having never actually used eval to process JSON, I incorrectly assumed my example would work. 从未实际使用eval处理JSON,我错误地认为我的示例可以工作。 It's fixed now with the addition of the surrounding braces. 现在已通过添加周围的括号来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM