Как убрать лишнюю запятую в JSON?

Всем привет. Мне нужно удалить последнюю запятую из строки. Я нашел regex, который выбирает как раз последнюю запятую, но в python оно, почему-то, убирает все запятые. re.sub(r'(,)(?!.*,)', '', str) regex

Было:

[
            { "key": "admin", "text": "Internal user" },
            { "key": "agent", "text": "Agent" },
            { "key": "corporate_landlord", "text": "Company Landlord" },
            { "key": "private_landlord", "text": "Landlord" },
            { "key": "tenant", "text": "Tenant" },
            { "key": "landlord", "text": "Landlord" },
            { "key": "none", "text": "None" },


        ]

Стало:

[
            { "key": "admin", "text": "Internal user" }
            { "key": "agent", "text": "Agent" }
            { "key": "corporate_landlord", "text": "Company Landlord" }
            { "key": "private_landlord", "text": "Landlord" }
            { "key": "tenant", "text": "Tenant" }
            { "key": "landlord", "text": "Landlord" }
            { "key": "none", "text": "None" }
        ]

Нужно:

[
        { "key": "admin", "text": "Internal user" },
        { "key": "agent", "text": "Agent" },
        { "key": "corporate_landlord", "text": "Company Landlord" },
        { "key": "private_landlord", "text": "Landlord" },
        { "key": "tenant", "text": "Tenant" },
        { "key": "landlord", "text": "Landlord" },
        { "key": "none", "text": "None" }


    ]

Ответы (1 шт):

Автор решения: Qwertiy

playground

import re

js = r"""[
  { "key": "admin", "text": "Internal user" },
  { "key": "agent", "text": "Agent" },
  { "key": "corporate_landlord", "text": "Company Landlord" },
  { "key": "private_landlord", "text": "Landlord" },
  { "key": "tenant", "text": "Tenant" },
  { "key": "landlord", "text": "Landlord" },
  { "key": "smth", "text": "Don\'t break \"}, ]\" in strings\\" },
  { "key": "none", "text": "None" },
]"""

json = re.sub(r',(\s*(?=[]}]|$))|("(?:[^\\"]|\\.)*"|[^"])', r'\1\2', js)

print(json)
[
  { "key": "admin", "text": "Internal user" },
  { "key": "agent", "text": "Agent" },
  { "key": "corporate_landlord", "text": "Company Landlord" },
  { "key": "private_landlord", "text": "Landlord" },
  { "key": "tenant", "text": "Tenant" },
  { "key": "landlord", "text": "Landlord" },
  { "key": "smth", "text": "Don\'t break \"}, ]\" in strings\\" },
  { "key": "none", "text": "None" }
]
→ Ссылка