Bluefire
Bluefire

Reputation: 14109

Eval doesn't work - JavaScript

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?

Upvotes: 1

Views: 1404

Answers (2)

Emil Stenström
Emil Stenström

Reputation: 14086

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

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318498

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.

Upvotes: 5

Related Questions