Parsing unquoted JSON string [duplicate]

2020-01-29 03:06发布

问题:

What is the easiest method to parse unquoted JSON string?
for example if I have the following:

{property1:value1,property2:value2}

The following throws an error:

JSON.parse( badJSONString );

since proper JSON should have keys and values quoted: {"property1":"value1"}

回答1:

If your data is consistent (and that might be a big if), you can process the string with a very simple function. The following will fail with certain strings that have commas or colons in the values or string like '{property1:val:ue1 ,property2:val,ue2}' but those are going to be problematic anyway without some delimiters in the data.

let bad = '{property1:value1,property2:value2}'
let obj = bad.slice(1, -1).split(/\s?,\s?/)
    .map(item => item.split(':'))
    .reduce((a, [key, val]) => Object.assign(a, {[key]: val}), {})

console.log(obj)



回答2:

An option could be the following:

var initial = "{property1:value1,property2:value2}"; // string (unquoted JSON)

var cleaned = initial.trim().substring(1, initial.length - 1); // remove `{` and `}`

var kvPair = cleaned.split(',');              // get an array like ["property1:value1", "property2:value2"]
var final = {};
var split;
for (var i = 0, l = kvPair.length; i < l; i++) {
  split = kvPair[i].split(':');               // get an array like ["property1","value1"]
  final[split[0].trim()] = split[1].trim();   // add value X to property X (remove whitespaces at the beginning and end)
}
console.log(final)

jsfiddle