Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative Array does not work with eval() JavaScript

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/

like image 250
ramdaz Avatar asked Nov 30 '22 08:11

ramdaz


2 Answers

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.

like image 39
David Titarenco Avatar answered Dec 23 '22 14:12

David Titarenco


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.

like image 54
hugomg Avatar answered Dec 23 '22 13:12

hugomg