Parsing "Relaxed" JSON Without Eval

Parse the json string without quotes into json

The main question is really where did you get the string from, but anyways, here is a solution.

var obj = eval('(' + str + ')');
var json = JSON.stringify(obj);

How to parse a NON JSON STRING to a Object in javascript

I've found a really cheeky way to do it

let obj = {}
eval("obj =" + '{ one: [1, 2, 3], num: 1 }')

Parsing unquoted JSON string

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)


Related Topics



Leave a reply



Submit