简体   繁体   English

JSON.parse与eval()

[英]JSON.parse vs. eval()

My Spider Sense warns me that using eval() to parse incoming JSON is a bad idea. 我的Spider Sense警告我,使用eval()解析传入的JSON是一个坏主意。 I'm just wondering if JSON.parse() - which I assume is a part of JavaScript and not a browser-specific function - is more secure. 我只是想知道JSON.parse() (我认为是JavaScript的一部分而不是浏览器特定的功能)是否更安全。

如果使用eval您更容易受到攻击 :JSON是Javascript和json的子集。parse仅解析JSON,而eval则为所有JS表达式敞开了大门。

All JSON.parse implementations most likely use eval() 所有JSON.parse实现JSON.parse可能使用eval()

JSON.parse is based on Douglas Crockford's solution , which uses eval() right there on line 497 . JSON.parse基于Douglas Crockford的解决方案 ,该解决方案第497行使用eval()

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

The advantage of JSON.parse is that it verifies the argument is correct JSON syntax. JSON.parse的优点是它可以验证参数是否为正确的JSON语法。

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. 并非所有浏览器都具有本机JSON支持,因此有时您需要对JSON字符串使用eval() Use JSON parser from http://json.org as that handles everything a lot easier for you. 使用来自http://json.org的 JSON解析器,因为它可以为您轻松处理所有事情。

Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!! Eval()是一个邪恶的行为,但是对某些浏览器来说却是一个必不可少的邪恶行为,但在可以避免的地方,请这样做!!!

There is a difference between what JSON.parse() and eval() will accept. JSON.parse()和eval()接受的内容有所不同。 Try eval on this: 尝试评估:

var x = "{\\"shoppingCartName\\":\\"shopping_cart:2000\\"}" var x =“ {\\” shoppingCartName \\“:\\” shopping_cart:2000 \\“}”

eval(x)         //won't work
JSON.parse(x)   //does work

See this example . 请参阅此示例

If you parse the JSON with eval , you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever. 如果使用eval解析JSON,则允许所解析的字符串包含绝对的任何内容,因此,您不仅可以发现自己执行的是函数调用,还可以执行其他操作,而不仅仅是一组数据。

Also, JSON's parse accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here ) 此外,JSON的parse接受一个aditional的参数,齐磊,让您指定如何(更多信息和示例在线文档处理某些价值观,如日期时间在这里

JSON is just a subset of JavaScript. JSON只是JavaScript的一个子集。 But eval evaluates the full JavaScript language and not just the subset that's JSON. 但是eval评估完整的JavaScript语言,而不只是JSON子集。

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

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