Andurit Andurit - 1 year ago 118
JSON Question

Make valid JSON from JSON like string - Regex?

I have JSON like string which looks like:


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.

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?

From json above my valid JSON should looks like:

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

Answer Source

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"')));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download