Last updated: Apr 8, 2024
Reading timeยท2 min
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.
import json my_json = r'{"name": "Bobby", "tasks": null, "age": null}' my_dict = json.loads(my_json) print(type(my_dict)) # ๐๏ธ <class 'dict'> print(my_dict) # ๐๏ธ {'name': 'Bobby', '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.
import json json_str = r'{"name": "Bobby", "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.
import json my_json = r'{"name": "Bobby", "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': 'Bobby', '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": "Bobby", "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.
import json my_dict = {'name': 'Bobby', None: None} print(my_dict) # ๐๏ธ {'name': 'Bobby', None: None} my_json = json.dumps(my_dict) print(my_json) # ๐๏ธ '{"name": "Bobby", "null": null}' my_dict_again = json.loads(my_json) print(my_dict_again) # ๐๏ธ {'name': 'Bobby', '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 were converted
to null
.
When we parsed the JSON string into a Python object, the value was converted to
None
, but the key is still the string null
.
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.
You can learn more about the related topics by checking out the following tutorials: