问题
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