Eval() = Unexpected token : error

此生再无相见时 提交于 2019-11-28 23:26:13
Jonathan M

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

Martin Varta

You have to write like this

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

to convert an string to Object

Hope I help!

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.

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"]}');

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...}');
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''

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

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