Why eval fails here?

烈酒焚心 提交于 2019-12-23 01:43:13

问题


0001: response
$[0] = [string] "{\"code\":200,\"id\":121}"
0001: eval(response)
SyntaxError: invalid label

Anyone knows?


回答1:


You have to wrap it in () to trigger expression evaluation, like this:

eval("(" + response + ")")

You can test it out here.


Though a better method is native JSON handling:

var result = JSON.parse(response);

Just include json2.js for older browser (< IE8) support, the call is the same...it just adds the global JSON object if it's missing.




回答2:


You need to wrap the JSON string in parentheses.

Otherwise, the { ... } is interpreted as a block of executable statements, which it isn't.

By surrounding it in parentheses, you force the interpreter to interpret it as an expression.



来源:https://stackoverflow.com/questions/4305003/why-eval-fails-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!