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/
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.
Your error is because a {
at the beggining of a statement is read as a code block (like the kind you use in if
s and for
s) 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With