Eval() = Unexpected token : error

前端 未结 8 1784
囚心锁ツ
囚心锁ツ 2020-12-09 04:28

I tried this simple JavaScript code:

eval(\'{\"Topics\":[\"toto\",\"tata\",\"titi\"]}\')

In the Chrome console, for example, this returns

相关标签:
8条回答
  • 2020-12-09 04:38

    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''
    
    0 讨论(0)
  • 2020-12-09 04:41

    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"]}');
    
    0 讨论(0)
  • 2020-12-09 04:42

    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...}');
    
    0 讨论(0)
  • 2020-12-09 04:46

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

    0 讨论(0)
  • 2020-12-09 04:46

    if you want to make an array use the below code

    var jsonObject = eval('(' +"["+ response + "]"+')');
    
    0 讨论(0)
  • 2020-12-09 04:58

    You have to write like this

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

    to convert an string to Object

    Hope I help!

    0 讨论(0)
提交回复
热议问题