Search code examples
regexregexp-replace

Regex: Replace all occurrences of an attribute from an object/dictionary/json?


I have an input attribute key value and I want to remove all its occurences from a json/dictionary/object. Here's an example:

{
 "$type":"NewRunner.SingleValueExpression",
 "name":"ABC",
 "age":23
 "nestedJSON": {
      "$type":"NewRunner.SingleValueExpression003",
      "field3":"edvrvbte"
    }
}

I want to remove "$type" attribute from everywhere in the given string and the output should be:

{
 
 "name":"ABC",
 "age":23
 "nestedJSON": {
    
      "field3":"edvrvbte"
    }
}

How can I write a regex for the same? Can someone help me?

Ideally it would be like: string.replace("regexValue",replacement)

I am looking for writing the regex value.

I tried this:

\"\$type\":\".+?(?=abc)\",

and this as well:

\"\$type\":\"(?<=\[)(.*?)(?=\])\",

But confused what should I write in center \".+?(?=abc)\" to match anything in value


Solution

  • Try this:

    "\$type":[^,{}]*,[\r\n]*|,\s*"\$type":[^{},\r\n]*
    

    "\$type":[^,{}]*,[\r\n]*

    • "\$type": match the string "$type":.

    • [^,{}]* match zero or more character except , this is important and it means that every character will be matched except , because we don't want to cross the comma. The same thing with the curly braces {} we don't want to cross the curly braces as well.

    • ,[\r\n]* match a literal , and zero or more newline.

    |,\s*"\$type":[^{},\r\n]*

    • | this is the alternation operator it is like Boolean OR.
    • ,\s* to match a comma followed by zero or more whitespace character.
    • "\$type": this part is the same as the previous part.
    • [^{},\r\n]* this part also the same as the previous part but here we added \r and \n and there is no comma , this is because if the value "$type":"NewRunner.SingleValueExpression" happens to be the last value in the object there will be no comma after it, but the problem here is that after the last value in the object there will be an optional new line or a closing curly brace } so we don't want to cross the closing curly brace as well. here we added \r and \n because if the value is the last value we don't want to remove the new line after it, this is not an important thing but to make the code looks good and the closing curly brace will be at that new line.

    See regex demo.