Jun 13
Over the past few weeks I've noticed forums and blogs near and far having discussions on how to safely parse JSON in JavaScript. Most of these conversations hinge upon something like "because eval is simply not enough." And they are right.
So, how do you safely parse JSON in JavaScript? Luckily for us, Doug Crockford has done the work for us. Simply include his json.js in your project, and all String objects will have a safe parseJSON method. It uses a regular expression to weed out malformed and possibly malicious JavaScript.
In addition, you'll also find that the Array, Boolean, Date, Number, Object and String types have a toJSONString method that converts a JavaScript value to a JSON value.
Here's a quick and dirty example:
var json = {
'foo': 12,
'bar': 'beer',
'baz': ['fish', 'fleas', 'fools']
}.toJSONString();
console.log(json); // Prints JSON string
// Safely parse JSON string
json = json.parseJSON();
console.log(json); // Prints JSON object
Further comments on this article have been disabled.



