我希望这个小函数将无效的 JSON 字符串转换为有效的字符串。
function JSONize(str) {
return str
// wrap keys without quote with valid double quote
.replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":'})
// replacing single quote wrapped ones to double quote
.replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"'})
}
结果
let invalidJSON = "{ hello: 'world',foo:1, bar : '2', foo1: 1, _bar : 2, $2: 3, 'xxx': 5, \"fuz\": 4, places: ['Africa', 'America', 'Asia', 'Australia'] }"
JSON.parse(invalidJSON)
//Result: Uncaught SyntaxError: Unexpected token h VM1058:2
JSON.parse(JSONize(invalidJSON))
//Result: Object {hello: "world", foo: 1, bar: "2", foo1: 1, _bar: 2…}