简体   繁体   English

将eval()转换为JSON.parse

[英]Convert eval() to JSON.parse

I was going through the ill-effects of using eval() with respect to XSS based attacks. 对于基于XSS的攻击,我正在经历使用eval()带来的不良影响。 There is a piece of code which I need to protect against a possible XSS attack, and what I guess that JSON.parse() should work fine. 我需要保护一段代码以防止可能的XSS攻击,而我认为JSON.parse()应该可以正常工作。

var request = new XMLHttpRequest(); 
var url = encDataPath + "/jcr:content/metadata.json?_charset_=utf-8";
url = Granite.HTTP.externalize(url);
request.open("GET", url ,false);
request.send(null);

var jsonData =eval("(" + request.responseText + ")"); // <-- here
var assetTitle = jsonData["dc:title"];
var mimetype = jsonData["dc:format"];

Can someone advise how can I change the eval() (for jsonData) to JSON.parse? 有人可以建议如何将eval() (用于jsonData)更改为JSON.parse吗?

Just replace that line with: 只需将该行替换为:

var jsonData = JSON.parse(request.responseText);

Provided the response is proper JSON, this should just work. 只要响应是正确的JSON,就可以正常工作。

Assuming that the response is well-behaved JSON, you would be able to simply replace the eval line with: 假设响应是行为良好的JSON,您将可以简单地将eval行替换为:

var jsonData = JSON.parse(request.responseText);

Beware though: the JSON parser is very restrictive in the values that it will accept, compared to the Javascript objects that eval would accept. 但是要当心:与eval可以接受的Javascript对象相比,JSON解析器在接受的值上有严格的限制。 For instance, 例如,

var jsVal = eval("({a:3})");

will result in the Object {a: 3}, whereas 将导致对象{a:3},而

var jsonVal = JSON.parse("{a:3}");

will result in a parse error because the JSON specification[0] requires object keys to be provided as double-quoted strings: 将导致解析错误,因为JSON规范[0]要求将对象键提供为双引号字符串:

var jsonVal = JSON.parse('{"a":3}');

If the server is properly configured it will generally output compliant JSON but it is something to be aware of. 如果服务器配置正确,通常将输出兼容的JSON,但这是需要注意的。

[0] http://www.json.org/ [0] http://www.json.org/

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

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