1

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()

{
  "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.

Daniel Trugman
  • 8,186
  • 20
  • 41
J-Coder
  • 13
  • 5
  • 1
    Python's `json.loads()` shouldn't _ever_ translate `null` to `"None"`; it should only translate it to `None` **without the quotes**, which is how Python writes the value that JavaScript calls `null`. Can you show the specific code you're using to invoke `loads()`, so we can cause this problem ourselves? – Charles Duffy Jun 19 '22 at 16:17
  • @J-Coder a small snippet of working code will provide more clarity – Aakash Verma Jun 19 '22 at 16:22

1 Answers1

2

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": []
}
Daniel Trugman
  • 8,186
  • 20
  • 41