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.

2
  • 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? Commented Jun 19, 2022 at 16:17
  • @J-Coder a small snippet of working code will provide more clarity Commented Jun 19, 2022 at 16:22

1 Answer 1

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": []
}
Sign up to request clarification or add additional context in comments.

1 Comment

I should have know that, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.