用于解析JSON的JavaScript eval()的替代方法 [英] Alternatives to JavaScript eval() for parsing JSON

查看:120
本文介绍了用于解析JSON的JavaScript eval()的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题。 JavaScript中的Eval是不安全的,不是吗?我有一个JSON对象作为字符串,我需要把它变成一个实际的对象,所以我可以获得数据:

Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data:

function PopulateSeriesFields(result) 
{
    data = eval('(' + result + ')');
    var myFakeExample = data.exampleType
}

如果它有助于我使用来自jQuery的$ .ajax方法。

If it helps I am using the $.ajax method from jQuery.

谢谢

推荐答案

,安全与否,当您使用jQuery时,最好使用 $ .getJSON() 方法,而不是$ .ajax():

Well, safe or not, when you are using jQuery, you're better to use the $.getJSON() method, not $.ajax():

$.getJSON(url, function(data){
    alert(data.exampleType);
});

eval()通常被认为是安全的当您只与自己的服务器进行通信时进行JSON解析,特别是当您在服务器端使用一个好的JSON库时,可以保证生成的JSON不会包含任何令人讨厌的内容。

eval() is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty.

Even JSON的作者Douglas Crockford表示,除了解析JSON之外,你不应该在代码中的任何地方使用 eval()。请参阅他的书中的相应部分 JavaScript:好的部件

Even Douglas Crockford, the author of JSON, said that you shouldn't use eval() anywhere in your code, except for parsing JSON. See the corresponding section in his book JavaScript: The Good Parts

这篇关于用于解析JSON的JavaScript eval()的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆