Daniel Bertoldi
Daniel Bertoldi

Reputation: 359

How to check if the value of the last key of a JSON ends with a comma using RegEx?

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

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

You can try

\,(\s*)(?=\}|])

enter image description here

Replace by \1

Regex demo

Upvotes: 1

blhsing
blhsing

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

Nick Reed
Nick Reed

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.

Demo

Upvotes: 1

Related Questions