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

查看:37
本文介绍了用于解析 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.

即使是 JSON 的作者 Douglas Crockford 也说你不应该在你的代码中的任何地方使用 eval(),除了解析 JSON.请参阅他的书中的相应部分

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天全站免登陆