Eval() = Unexpected token : error

不羁的心 提交于 2019-12-29 04:36:11

问题


I tried this simple JavaScript code:

eval('{"Topics":["toto","tata","titi"]}')

In the Chrome console, for example, this returns

SyntaxError: Unexpected token :

I tried the JSON on JSONLint and it's valid.

Do you see the bug?


回答1:


FWIW, use JSON.parse instead. Safer than eval.




回答2:


You have to write like this

eval('('+stingJson+')' );

to convert an string to Object

Hope I help!




回答3:


Because eval does not force an expression context and the string provided is an invalid JavaScript program, thus the first three tokens (and how they are looked at) are:

{            // <-- 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.




回答4:


Number one: Do not use eval.

Number two. Only use eval to make something, well be evaluated. Like for example:

eval('var topics = {"Topics":["toto","tata","titi"]}');



回答5:


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('var x = {"Topics":etc...}');



回答6:


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''



回答7:


if you are using JQuery use the function $.parseJSON(), worked for me, had the same problem



来源:https://stackoverflow.com/questions/7985450/eval-unexpected-token-error

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