-1

I am looking to clean up a JSON string from attributes that contain a particular property. In the following example I want to remove attributes whose values are objects with the "_href" property.

Original string:

[{
    "name": "Test",
    "junkAttributeA": {
      "_href": "string",
      "_type": "string"
    },
    "junkAttributeB": {
      "_href": "string",
      "_type": "string"
    }
}]

Resulting string:

[{
    "name": "Test"
}]

What RegEx pattern should I use to detect the unwanted attributes?

Mossi
  • 997
  • 5
  • 15
  • 28
  • Surely your language has a JSON parser which will then allow you to modify the resultant object and write out a new JSON string? That will be a lot easier than trying to use regex for this problem. – Nick Apr 07 '20 at 03:28
  • @Nick The problem is, this is a huge JSON response from a REST API and it needs to be serialized in memory. I have already used a JSON parser and it was not fast enough (or maybe I didn't do it properly?) so thought to "normalize" it before the fact. – Mossi Apr 07 '20 at 03:54
  • I see the question has been closed (and down-voted). It's okay; @virolino's answer does it for me. But I had tried all sorts of regex patterns to no avail. And I had used regexr.com and other helpers to figure this out. So the recommended answer (general regex reference) isn't helpful.. Some people have the knowledge (and have tried) but just aren't experts and need more experience to unwrap challenging problems. You all probably traversed the same path to become regex gurus. That's why unlike other SE forums I rarely post on SO. It's a discouraging place. And I have been coding for 13 years.. – Mossi Apr 07 '20 at 17:02

1 Answers1

1

Note: the best solution is a proper parser. It will do the work in the proper way, nicely.


A regex to detect your attributes is:

"[^"{}]+":\s*{[^{}]*"_href":[^{}]*}

Replace that regex with the empty string.

Note: after removing the attributes, you will have to do some additional parses to remove the unnecessary commas. That is one of the reasons to use a proper parser.

Test here.

virolino
  • 2,073
  • 5
  • 21