Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"}'

try:
    print(json.loads(invalid))
except json.JSONDecodeError as e:
    print(e)

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading