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