Skip to content Skip to sidebar Skip to footer

Parsing Unquoted JSON String

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( badJS

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

Solution 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


Post a Comment for "Parsing Unquoted JSON String"