当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

You already know this, since you referred me here =D, 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 can't quote keys when writing the string, you can insert quotes before using JSON.parse-

var s= "{muh: 2,mah:3,moh:4}";
s= s.replace(/([a-z][^:]*)(?=\s*:)/g, '"$1"');

var o= JSON.parse(s);
/*  returned value:[object Object] */
JSON.stringify(o)
/*  returned value: (String){
    "muh":2, "mah":3, "moh":4
}
网友答案:

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);
网友答案:

This is what I ended up having to do. I extended @ArnaudWeil's answer and added support for having : appear in the values:

var badJSON = '{one : "1:1", two : { three: \'3:3\' }}';

var fixedJSON = badJSON.replace(/:\s*"([^"]*)"/g, function(match, p1) {return ': "' + p1.replace(/:/g, '@[email protected]') + '"';}).replace(/:\s*'([^']*)'/g, function(match, p1) {return ': "' + p1.replace(/:/g, '@[email protected]') + '"';}).replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ').replace(/@[email protected]/g, ':')
;

console.log('Before: ' + badJSON);
console.log('After: ' + fixedJSON);
console.log(JSON.parse(fixedJSON));
分享给朋友:
您可能感兴趣的文章:
随机阅读: