Andurit
Andurit

Reputation: 5762

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

Upvotes: 2

Views: 842

Answers (3)

Phil
Phil

Reputation: 165062

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

Upvotes: 1

Keith
Keith

Reputation: 24241

Would this be ok. ->

function makeJsonString(v) {
    var s = v.split(/({|}|:|,)/g).
        filter(function (e) { return e.length !== 0 }),
        r = '{}:,';
    for (var l = 0; l < s.length; l ++) {
        var x = s[l];
        if (r.indexOf(x) < 0) {
           s[l] = '"' + s[l] + '"';
        }
    }
    return s.join('');
}

var x = makeJsonString('{key1:my.value1,key2:value2}');
//parse check
console.log(JSON.parse(x));

Example -> Fiddle

Upvotes: 1

Matthias
Matthias

Reputation: 2785

If it's always in that format, I would probably do something like:

  • Trim the curly Brackets
  • Split the remaining string by ,, then you get an array like this: ['key:my.value1', 'key2:my.value2']
  • iterate over all entries in that list, and split each of them by :, which would give you the key/value pairs

If all you need is to iterate over the entires, then you're ready to go. if you want to convert it to json, create a new map and put the key/value pairs to it.

Upvotes: 2

Related Questions