Python json load none
Last updated: Feb 18, 2023
Reading time · 2 min
# 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.
Copied!import json my_json = r'' my_dict = json.loads(my_json) print(type(my_dict)) # 👉️ print(my_dict) # 👉️
The example shows how to convert null values to None using the json.loads() method.
# Convert JSON NULL values to Python None values
The json.loads method parses a JSON string into a native Python object.
Copied!import json json_str = r'' my_dict = json.loads(json_str) print(type(my_dict)) # 👉️
The process of converting a JSON string to a native Python object is called deserialization.
# Convert Python None values to JSON NULL values
You can use the json.dumps method to convert a Python object to a JSON formatted string.
Copied!import json my_json = r'' # ✅ convert NULL values to None (JSON string to Python object) my_dict = json.loads(my_json) print(type(my_dict)) # 👉️ print(my_dict) # 👉️ # ✅ convert None to null (Python object to JSON string) my_json_again = json.dumps(my_dict) print(my_json_again) # 👉️ ''
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.
Copied!import json my_dict = 'name': 'Bobby', None: None> print(my_dict) # 👉️ my_json = json.dumps(my_dict) print(my_json) # 👉️ '' my_dict_again = json.loads(my_json) print(my_dict_again) # 👉️
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.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.