views:

1463

answers:

3

I've got an array of objects in json format: [{"name":"obj1", "list":["elem1", "elem2", "elem3"]}, {"name":"obj2", "list":["elem4", "elem5", "elem6"]}]

Now I'd like to construct regexp to remove quotation marks from around elements in the "list" using javascript.

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

+1  A: 

This works, but it's not pure regex:

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 list substrings; and second, remove the apostrophes from them.

You could do this with pure regex if javascript supported variable length lookbehind, which it doesn't.

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

It doesn't support lookbehind at all, actually... :-)
PhiLho
It might be desirable to remove only outer quotes, leaving escaped quotes intact: return ....replace(/([^\\])"/g, '$1');
Victor
A: 

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 substituting the strings afterwards might be a better way.

For example if they are all DOM element id values then after converting the JSON string to an object you could just do object["list"][0] = document.getElementById(object["list"][0]) or what ever makes sense for your object.

atetlaw
A: 

This should solve the problem as you described it:

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

After matching a quotation mark, the lookahead checks that there's a closing square bracket up ahead, but no opening bracket between it and the current position. If the JSON is well-formed, that means the opening bracket is before the current position, so the match occurred inside a list.

Alan Moore