Javascript Eval() = 意外标记:错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7985450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eval() = Unexpected token : error
提问by Tuizi
I tried this simple JavaScript code:
我尝试了这个简单的 JavaScript 代码:
eval('{"Topics":["toto","tata","titi"]}')
In the Chrome console, for example, this returns
例如,在 Chrome 控制台中,这将返回
SyntaxError: Unexpected token :
语法错误:意外标记:
I tried the JSON on JSONLintand it's valid.
我在JSONLint上尝试了 JSON ,它是有效的。
Do you see the bug?
你看到错误了吗?
采纳答案by Jonathan M
FWIW, use JSON.parse
instead. Safer than eval
.
FWIW,请JSON.parse
改用。比eval
.
回答by Martin Varta
You have to write like this
你必须这样写
eval('('+stingJson+')' );
to convert an string to Object
将字符串转换为对象
Hope I help!
希望我有所帮助!
回答by Martin Varta
Because eval
does notforce an expression context and the string provided is an invalidJavaScript program, thus the first three tokens (and how they are looked at) are:
因为eval
不强制表达式上下文并且提供的字符串是无效的JavaScript 程序,因此前三个标记(以及它们的查看方式)是:
{ // <-- beginning of a block, and NOT an Object literal
"Topics" // <-- string value, okay (note this is NOT a label)
: // <-- huh? expecting ";" or "}" or an operator, etc.
Happy coding.
快乐编码。
回答by Naftali aka Neal
Number one: Do not use eval.
第一:不要使用 eval。
Number two. Only use eval to make something, well be evaluated. Like for example:
第二。只使用 eval 来制作一些东西,很好被评估。例如:
eval('var topics = {"Topics":["toto","tata","titi"]}');
回答by Marc B
Because that's evaluating an object. eval() requires you to pass in syntactically valid javascript, and all you're doing is passing in a bare object. The call should be more like:
因为那是在评估一个对象。eval() 要求您传入语法上有效的javascript,而您所做的只是传入一个裸对象。调用应该更像是:
eval('var x = {"Topics":etc...}');
回答by Pica Mio
USE:
用:
function evalJson(jsArray){ eval("function x(){ return "+ jsArray +"; }"); return x(); }
var yourJson =evalJson('{"Topics":["toto","tata","titi"]}');
console.log(yourJson.Topics[1]); // print 'tata''
回答by Mark E
if you are using JQuery use the function $.parseJSON()
, worked for me, had the same problem
如果您使用的是 JQuery,请使用$.parseJSON()
为我工作的函数,遇到同样的问题