Convert JSON NULL values to None using Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Convert JSON NULL values to None using Python #

Use the json.loads() method to convert JSON NULL values to None in Python. The json.loads method parses a JSON string into a native Python object. Conversely, the json.dumps method converts a Python object to a JSON formatted string.

main.py
import json my_json = r'{"name": "Alice", "tasks": null, "age": null}' my_dict = json.loads(my_json) print(type(my_dict)) # 👉️ <class 'dict'> print(my_dict) # 👉️ {'name': 'Alice', 'tasks': None, 'age': None}

The example shows how to convert null values to None using the json.loads() method.

The json.loads method parses a JSON string into a native Python object.

main.py
import json json_str = r'{"name": "Alice", "age": 30}' my_dict = json.loads(json_str) print(type(my_dict)) # 👉️ <class 'dict'>

The process of converting a JSON string to a native Python object is called deserialization.

You can use the json.dumps method to convert a Python object to a JSON formatted string.

main.py
import json my_json = r'{"name": "Alice", "tasks": null, "age": null}' # ✅ convert NULL values to None (JSON string to Python object) my_dict = json.loads(my_json) print(type(my_dict)) # 👉️ <class 'dict'> print(my_dict) # 👉️ {'name': 'Alice', 'tasks': None, 'age': None} # ✅ convert None to null (Python object to JSON string) my_json_again = json.dumps(my_dict) print(my_json_again) # 👉️ '{"name": "Alice", "tasks": null, "age": null}'

The process of converting a native Python object to a JSON string is called serialization.

You can also have None keys in Python objects, but it should generally be avoided.

main.py
import json my_dict = {'name': 'Alice', None: None} print(my_dict) # 👉️ {'name': 'Alice', None: None} my_json = json.dumps(my_dict) print(my_json) # 👉️ '{"name": "Alice", "null": null}' my_dict_again = json.loads(my_json) print(my_dict_again) # 👉️ {'name': 'Alice', 'null': None}

We started with a Python object that has a None key and a None value.

When we converted the object to JSON, both the key and the value got converted to null.

When we parsed the JSON string into a Python object, the value got converted to None, but the key is still the string null.

This is because JSON keys must be of type string. If we pass a key of any other type to the json.dumps() method, the key automatically gets converted to a string.

Once the key is converted to a string, parsing the JSON string will return a string key in the Python object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.