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?
When using
evalyou need to wrap the JSON in():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 toJSON.parse.Note that you should include
json2.jswhen usingJSON.*since some older browser do not have native JSON support.