Parsing unquoted JSON string [duplicate]

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"}

Answers:

Answer

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)

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.