Imagine I have a string representing a JSON object. It could be invalid, with some params that will be replaced by another system (e.g. %param%). The task at hand is to remove all objects with a known propertyName equal to "true" using regex.
{
"someTopLevelProp": "value",
"arrayOfData": [
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": $paramValue$,
"dontCareProp2": 2,
"flagWhichShouldIUse": true,
"somethingAtTheEnd": "value"
},
{
"absolutelyAnotherObject": %paramValue%
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": false,
"somethingAtTheEnd": "value"
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": true,
"somethingAtTheEnd": "value"
}
]
}
In the scenario above, there's always "firstPropIAlwaysKnow" which indicates that the object may contain the flag that needs removal. Subsequent properties may follow. The crucial factor is "flagWhichShouldIUse", signifying the object for deletion (only if value is 'true'). The desired result should be:
{
"someTopLevelProp": "value",
"arrayOfData": [
{
"absolutelyAnotherObject": %paramValue%
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": false,
"somethingAtTheEnd": "value"
}
]
}
My regex skills are not proficient enough, so seeking help from the community.
P.S. Refrain from stating that parsing JSON with regex is a crazy\incorrect\bad idea - rest assured, I am aware of that.
ANSWER: I now possess a functional regex that accomplishes the task. Gratitude to everyone who offered assistance. It may prove beneficial to others as well.
/{\s+?"firstPropIAlwaysKnow": "value"[^{}]+?(?:\{[^}]*\}[^}]+?)*[^}]+?"flagWhichShouldIUse": true[^}]+?},?/gi
Regexper