Regexp: remove quotes from json list

I have an array of objects in json format:

[
    {
        "name": "obj1",
        "list": [
            "elem1",
            "elem2",
            "elem3"
        ]
    },
    {
        "name": "obj2",
        "list": [
            "elem4",
            "elem5",
            "elem6"
        ]
    }
]

      

Now I would like to create a regexp to remove quotes from all items in a "list" using javascript.

Desired output:

[{"name":"obj1", "list":[elem1, elem2, elem3]},
 {"name":"obj2", "list":[elem4, elem5, elem6]}]

      

0


source to share


3 answers


This works, but this is not a pure expression:

var str = '[{"name":"obj1", "list":["elem1", "elem2", "elem3"]},'
        + '{"name":"obj2", "list":["elem4", "elem5", "elem6"]}]';
str = str.replace(/"list":\[[^\]]+\]/g, function (match) {
    return '"list":' + match.substring(7, match.length).replace(/([^\\])"/g, '$1');
});
document.write(str);

      

Basically, it divides the process into two: first, find the substrings of the list; and second, remove the apostrophes from them.



You can do this with a pure regex if javascript supports variable lookbehind length, which it doesn't.

Edited to allow escaped apostrophes in list items as suggested by MrP.

+1


source


If [elem1, elem2, elem3] are to become references to DOM elements, or even existing variables, then perhaps converting your JSON string to a JavaScript object and then replacing the strings might be a better way.



For example, if these are all DOM element id values, then after converting the JSON string to an object, you can just do object["list"][0] = document.getElementById(object["list"][0])

or whatever ever makes sense for your object.

+1


source


This should fix the problem as you described it:

str = str.replace(/"(?=[^\[]*\])/g, '');

      

After matching the quote, the control panel checks to see if there is a closing square bracket in front, but no open parenthesis between it and the current position. If the JSON is well formed, it means that the open parenthesis is before the current position, so the match happened inside the list.

0


source







All Articles