Regex Remove Json Property
I'd like to remove a stringfied json's property based on its key wherever it is, whatever its value type is. But removing it only if its value is a string and its on the root level
Solution 1:
If you have any way of using a parser it's a more stable and readable solution. The regex \s*\"attr\" *: *\".*\"(,|(?=\s*\}))
should be shorter and better.
Several changes I made to help:
- Don't use so many character classes like
[,]
. If there is only one element in a character class it should be left by itself. - Only use numbered counts when required. Ex:
{0,1}
is?
and{1}
is pointless. - Instead of searching for a comma in the previous line to see if it is the end of a list checking if there is a
}
following the line allows you to group the conditionals together. - A positive lookahead is used at the end to search for
}
so it wouldn't be removed during the substitution.
Update with bugfix mentioned in comments. Trailing commas would be left if the attribute is last. The simplest way I found to fix this was to match both cases. So, you'll have to fill in attr twice.
(,\s*\"attr\" *: *\".*\"|(?=\s*\}))|(\s*\"attr\" *: *\".*\"(,|(?=\s*\})))
Solution 2:
I modified the regex from the first example, it works better even if is Flat JSON
\s*\"attr\" *: *(\"(.*?)\"(,|\s|)|\s*\{(.*?)\}(,|\s|))
Post a Comment for "Regex Remove Json Property"