2

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"
}
2
  • Are we to assume my, my.value1 and value2 are all defined in the current scope? Commented Sep 26, 2016 at 10:00
  • Hi @Phil it's actualy string so values should be always string as well, Please check my edit Commented Sep 26, 2016 at 10:00

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice way how to do it :) I peronaly pref @Phill one however you got my thumb up for this solution.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.