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

Keeping null value after json.load() in Python

I loaded a JSON file through json.load(file) and edited it.
I want to send a requests with json=payload that has some null values. But, after loading it in python, it became "None".

My question is how do I keeping null and without converting to "None" to send the requests.

Example:
Before json.loads()

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

{
  "key1": 10,
  "key2": "Comes and Goes",
  "key3": null,
  "key4": null,
  "key5": null,
  "key6": []
}

After json.load()

{
  "key1": 10,
  "key2": "Comes and Goes",
  "key3": None,
  "key4": None,
  "key5": None,
  "key6": []
}

But what I really want after json.load() is:

{
  "key1": 10,
  "key2": "Comes and Goes",
  "key3": null,
  "key4": null,
  "key5": null,
  "key6": []    
}

Any help is appreciatted! Thanks in advance.

>Solution :

When you do json.load you are converting the JSON object into a Python object. I.e. JSON objects are converted into dicts, JSON arrays into Python lists, etc.

Python’s null value is None, and that’s the conversion you should expect. When you convert it back using json.dump, you’ll get the same null-s back.

Consider this small snippet:

with open('in.json') as fin:
    data = json.load(fin)

print(data) # Print Python object
print(json.dumps(data, indent=4)) # Print output JSON

If the contents of in.json are:

{
    "key1": 10,
    "key2": "Comes and Goes",
    "key3": null,
    "key4": null,
    "key5": null,
    "key6": []
}

Printing the Python object results in:

{'key1': 10, 'key2': 'Comes and Goes', 'key3': None, 'key4': None, 'key5': None, 'key6': []}

And printing the json.dumps result in the exact same content as the input file:

{
    "key1": 10,
    "key2": "Comes and Goes",
    "key3": null,
    "key4": null,
    "key5": null,
    "key6": []
}
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