Eval() = Unexpected token : error

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?


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


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.


You have to write like this

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

to convert an string to Object

Hope I help!

链接地址: http://www.djcxy.com/p/8018.html

上一篇: 使用Chrome:未捕获的SyntaxError:意外的令牌<

下一篇: Eval()=意外标记:错误