Koshera Koshera - 2 months ago 19
JSON Question

JavaScript - regular expression to remove square brackets only at specific places

Is possible to remove the square brackets only at a specific place in a string? I have the following string:

[{
"text": "Text123",
"data": [{
"status": "Pending",
"validity": "Invalid"
}],
"children": [{
"text": "Text456",
"data": [{
"status": "Pending",
"validity": "Invalid"
}]
}]
}]


I need to remove the square brackets from the data array but keep them everywhere else. The result string should be:

[{
"text": "Text123",
"data": {
"status": "Active",
"validity": "Inactive"
},
"children": [{
"text": "Text456",
"data": {
"status": "Pending",
"validity": "Valid"
}
}]
}]


Is it possible to accomplish this with a regular expression?
Thanks!

Answer

Although I find the question a bit weired, but probably you have such a need. Anyway here is the regex:

/"data": \[([^\]]*)\]/g

then replace by:

"data": $1

Where \1 is the capturing group

Comments