Eval() = Unexpected token : error

37,973

Solution 1

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

Solution 2

You have to write like this

eval('('+stringJson+')' );

to convert an string to Object

Hope I help!

Solution 3

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

Solution 4

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

Solution 5

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''
Share:
37,973
Tuizi
Author by

Tuizi

Updated on July 09, 2022

Comments

  • Tuizi
    Tuizi almost 2 years

    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?

  • Patrick Jackson
    Patrick Jackson over 11 years
    works for me..don't know if it is the best practice, but it got me up and running
  • Kevin Beal
    Kevin Beal over 9 years
    This was the only solution that worked in my case. Thank you!
  • apocalypz
    apocalypz over 9 years
    thx, this is much better than accepted answer. It is good to point out that eval is evil :), but still, this answers the question.
  • Stephen Paul
    Stephen Paul about 7 years
    I had the same issue evaluating a normal javascript function and this solved my problem. Why / how does wrapping an expression in parenthesis fix the problem?
  • Mayur Gupta
    Mayur Gupta over 2 years
    This works for me