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
5 Answers
Reset to default 9Your 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.
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.