Andurit Andurit - 2 months ago 10
JSON Question

Make valid JSON from JSON like string - Regex?

I have JSON like string which looks like:

{key1:my.value1,key2:value2}


It could not have any nested object or arrays.
I can even prove it will be always like this with regex



var re = /^\{[A-Z0-9._]+:[A-Z0-9._]+(,[A-Z0-9._]+:[A-Z0-9._]+)*\}$/i;
console.log( re.test('{key1:my.value1,key2:value2}') ) // true





It looks really similar but it's not valid JSON so I can not iterate over it.

Question:
Is there a way how to make from this JSON like string valid JSON?

I was thinking about some regex or something but really not sure how to make it. Any advise?

Result:
From json above my valid JSON should looks like:

{
"key1": "my.value1",
"key2": "value2"
}

Answer

If you're sure of the format, you could simply create a JSON string by wrapping each key:value pair in quotes

var str = '{key1:my.value1,key2:value2}',
    rx = /([A-Z0-9._]+):([A-Z0-9._]+)/gi;

console.log(JSON.parse(str.replace(rx, '"$1":"$2"')));