Reputation: 359
I have the following JSON:
{
"markers": [
{
"name": "Rixos The Palm Dubai",
"position": [25.1212, 55.1535],
},
{
"name": "Shangri-La Hotel",
"description": "some description",
},
{
"value": 123445,
}
]
}
I'm trying to create a RegEx that can find all cases where the value of the last key or array ends with a ,
and remove it using Python and the re
library. In the JSON above, all values should have their commas removed.
I've already tried using \,[^.]+\}
So it can find arrays or objects ending with a value with a ,
but the RegEx doesn't stop after finding another ,
or {
for instance. Here's what I mean.
Now, I know I shouldn't be using RegEx to handle a JSON, but this is a very specific case and it won't cause any trouble.
Upvotes: 2
Views: 257
Reputation: 106618
You can use a positive lookahead pattern instead to match only a ,
that is followed by either a }
or a ]
with optional white spaces in between:
,(?=\s*[}\]])
Demo: https://regex101.com/r/xnBTCg/3
Upvotes: 2
Reputation: 5059
(?=^[^:\n]*:[^:\n]*$).*(,)(?=\s*[\}\]])$
This regex uses a positive lookahead to assert that on one line, there's a :
somewhere, which indicates the presence of a key-value pair for your data. The non-lookahead portion matches one comma at the end of a line. The final lookahead asserts that the next line contains only whitespace and a closing bracket or curly brace.
Upvotes: 1