1

I've never used eval() before, so I assume that I just got the syntax horribly wrong. What's wrong with the following:

var JSONAsString = '{"item1":"one", "item2":"two", "item3":"three"}';
var JSONAsObject = eval(JSONString);
alert(JSONAsObject.item1);

Since it doesn't seem to be working - I load the page and nothing happens.

And yes, I know I shouldn't be using eval. I assume that the syntax for JSON.parse() is the same as that of eval... right? If it is, if (after fixing the code) I replace eval with JSON.parse, will it still do the same thing?

5
  • JSONString vs JSONAsString, JSONAsObject vs JSONObject - your variable names are incorrect. Besides that, after parsing/evaluating it it's a JavaScript object, not JSON (just to be nitpicking ;)), so JSONObject doesn't really fit. Commented Jun 17, 2012 at 10:09
  • Assuming you have the variable names correct, evaling the string results in a syntax error because the {...} are interpreted as block and not as object literal. Commented Jun 17, 2012 at 10:11
  • @ThiefMaster - that's exactly why it's JSON as (an) object. Commented Jun 17, 2012 at 10:12
  • In line 3 you did not have the As in the variable name ;) Commented Jun 17, 2012 at 10:13
  • Oops... But it still doesn't work that way :D Commented Jun 17, 2012 at 10:18

2 Answers 2

5

When using eval you need to wrap the JSON in ():

var JSONAsString = '{"item1":"one", "item2":"two", "item3":"three"}';
var JSONAsObject = eval('(' + JSONAsString + ')');
alert(JSONAsObject.item1);

However, you should use JSON.parse() right from the beginning, not just later. Otherwise possibly invalid JSON that is valid JavaScript might work but stop working when switching to JSON.parse.

Note that you should include json2.js when using JSON.* since some older browser do not have native JSON support.

Sign up to request clarification or add additional context in comments.

6 Comments

Aah, thanks! Does that go for all code that I put into a variable and then parse using eval(), or just JSON?
Use JSON.parse() and forget the rest.
What @MaxArt says. But in any case, if you eval() an expression you'll want () around it to ensure it's not evaluated as a statement.
So yeah, about JSON.parse - does it require similar syntax? So, again, if I went into some code which used eval to parse JSON and replaced it with JSON.parse, without changing anything else, would that still be fine?
Yes, you simply use JSON.parse(some_string_containgin_json)
|
3

Don't use eval() to parse JSON. Use Douglas Crockfords json2, which gives you cross-browser support, performance and security: https://github.com/douglascrockford/JSON-js

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.