What is the easiest method to parse "relaxed" JSON but avoid evil eval
?
The following throws an error:
JSON.parse("{muh: 2}");
since proper JSON should have keys quoted: {"muh": 2}
My use case is a simple test interface I use to write JSON commands to my node server. So far I simply used eval
as it's just a test application anyway. However, using JSHint on the whole project keeps bugging me about that eval
. So I'd like a safe alternative that still allows relaxed syntax for keys.
PS: I don't want to write a parser myself just for the sake of the test application :-)
Your server could be compromised and the data source could be tampered with.
JSON is derived from JavaScript and its syntax is mostly a subset of the language, it is often possible to use the JavaScript eval() function to parse JSON data.
The eval() function in JavaScript is used to take an expression and return the string. As a result, it can be used to convert the string into JSON.
That makes the regex to remove the quotes from the keys MUCH easier. Start your solution with this: var cleaned = JSON. stringify(x, null, 2);
You could sanitize the JSON using a regular expression replace:
var badJson = "{muh: 2}"; var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": '); JSON.parse(correctJson);
You already know this, since you referred me here, but I figure it might be good to document it here:
I'd long had the same desire to be able to write "relaxed" JSON that was still valid JS, so I took Douglas Crockford's eval-free json_parse.js and extended it to support ES5 features:
https://github.com/aseemk/json5
This module is available on npm and can be used as a drop-in replacement for the native JSON.parse()
method. (Its stringify()
outputs regular JSON.)
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With