Empty key value in JSON

I’m trying to parse a string list to JSON. When the list has items, the return is:
{'body': '{"A":"a", "B": ["abc"], "C":"c"}}'
Using json.dumps and then json.loads works out.

But when the list is empty, the return is:
{'body': '{"A":"a", "B": , "C": "c"}}'

I get a JSONDecodeError: Expecting value and can’t access the B key.

Access code: B_key = [] if body.get("B", []) == "" else json.dumps(body.get("B", []))

I know that it should be "B": "" or "B": [] but the platform i’m working with returns the blank value.

Is there a way to solve this?

>Solution :

Since you’re working with invalid JSON, you’d need to fix it before loading it.

The following regex fixes the example you gave into valid json ([{,]\s*?"[^"]+"\s*:)\s*,.

NB. it is never a good idea fixing JSON with regexes and while this works with the example you gave, it might break with other data, the way to fix this is fixing whatever produces the invalid JSON.

import json
import re

invalid = '{"A":"a", "B": , "C": "c"}'

except json.JSONDecodeError as e:

valid = re.sub(r'([{,]\s*?"[^"]+"\s*:)\s*,', r'\1 null,', invalid)

print(json.loads(valid))  # {'A': 'a', 'B': None, 'C': 'c'}

Leave a Reply