最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Associative Array does not work with eval() JavaScript - Stack Overflow

programmeradmin3浏览0评论

I am generating a data expressed as a Python dictionary which is dumped using simplejson via url which is in this format.

{"2": "London", "3": "Tokyo", "4": "Sydney"}

I am using $.get and storing into a variable data. However eval(data) does not generate an Associative Array. Actually throws up an error. What is the problem? What is the solution?

Edit: I have shared the code /

I am generating a data expressed as a Python dictionary which is dumped using simplejson via url which is in this format.

{"2": "London", "3": "Tokyo", "4": "Sydney"}

I am using $.get and storing into a variable data. However eval(data) does not generate an Associative Array. Actually throws up an error. What is the problem? What is the solution?

Edit: I have shared the code http://dpaste.com/570901/

Share Improve this question edited Jul 19, 2011 at 2:03 ChaosPandion 78.3k18 gold badges121 silver badges159 bronze badges asked Jul 18, 2011 at 19:23 ramdazramdaz 1,7912 gold badges22 silver badges44 bronze badges 1
  • eval("console.info(" + JSON.stringify('{"2": "London", "3": "Tokyo", "4": "Sydney"}')+")"); – Cyril Jacquart Commented Apr 6, 2023 at 21:02
Add a comment  | 

5 Answers 5

Reset to default 9

Your error is because a { at the beggining of a statement is read as a code block (like the kind you use in ifs and fors) and not as an object literal. You can put parenthesis around for the eval to do as you want:

eval('(' + str + ')');

Of course, eval is evil and you should use something like JSON.parse instead. Most new browsers have this and it is not only safer but faster.

We need to see more code...

var x = '{"2": "London", "3": "Tokyo", "4": "Sydney"}';

eval('var y = ' + x);
      // or
var y = eval('(' + x + ')');

console.log(y);
console.log(y["2"]);

The above works just fine. What exactly are you doing/not doing?

PS: You shouldn't use eval for this regardless, but it's important to know how it works.

eval is slow, inefficient and hard to debug. Don't use it.

Have your script output an application/json content-type header, and jQuery will convert JSON to a JS object automatically.

Remember that you are evaluating JavaScript code and not JSON. From the looks of it your string will evaluate to a block but the first portion is syntactically incorrect. ("2": is close to a labeled statement but no cigar.) You'll need to wrap the string in parentheses to treat it as an object literal.

with jquery's $.get() function, you can tell it to expect a json string back (set the 'dataType' as "json"), and it will take care of creating an object for you, no eval() required.

发布评论

评论列表(0)

  1. 暂无评论