Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing "relaxed" JSON without eval

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 :-)

like image 741
axkibe Avatar asked Mar 09 '12 16:03

axkibe


People also ask

Why JSON eval is not recommended for use?

Your server could be compromised and the data source could be tampered with.

Does JSON parse use eval?

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.

What does eval () method do in JSON?

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.

How do I remove quotes from JSON Stringify?

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);


2 Answers

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); 
like image 197
Arnaud Weil Avatar answered Sep 18 '22 23:09

Arnaud Weil


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!

like image 31
Aseem Kishore Avatar answered Sep 18 '22 23:09

Aseem Kishore