How to Convert Between JSON null and Python None
This guide explains the relationship between null in JSON and None in Python, and how to correctly convert between them using the json.loads() and json.dumps() methods. We'll cover the standard conversions and what happens when you try to use None as a dictionary key.
JSON null to Python None (json.loads)
The json.loads() function is used to deserialize a JSON string (convert it from a string to a Python object). When it encounters null in the JSON, it correctly converts it to Python's None:
import json
my_json = r'{"name": "Tom", "tasks": null, "age": null}'
my_dict = json.loads(my_json)
print(type(my_dict)) # Output: <class 'dict'>
print(my_dict) # Output: {'name': 'Tom', 'tasks': None, 'age': None}
json.loads(my_json): Parses the JSON stringmy_jsoninto a Python dictionary. Thenullvalues are automatically converted toNone.
Python None to JSON null (json.dumps)**
The json.dumps() function is used to serialize a Python object (like a dictionary) into a JSON string. When it encounters None in a Python object, it correctly converts it to null in the JSON:
import json
my_dict = {'name': 'Tom', 'tasks': None, 'age': None} # Python dictionary
my_json_again = json.dumps(my_dict) # Serialize to JSON string
print(my_json_again) # Output: {"name": "Tom", "tasks": null, "age": null}
json.dumps(my_dict): Converts the Python dictionarymy_dictto a JSON string. TheNonevalues are automatically converted tonull.
None as a Dictionary Key (Avoid)
While Python technically allows None as a dictionary key, it's strongly discouraged and leads to confusing and potentially problematic behavior when interacting with JSON:
import json
my_dict = {'name': 'Tom', None: None}
print(my_dict) # Output: {'name': 'Tom', None: None}
my_json = json.dumps(my_dict) # Keys get converted to strings.
print(my_json) # Output: '{"name": "Tom", "null": null}'
my_dict_again = json.loads(my_json)
print(my_dict_again) # Output: {'name': 'Tom', 'null': None}
- Python: In Python,
Nonecan be a dictionary key. json.dumps(): When serializing to JSON,json.dumps()converts theNonekey to the string"null". This is because JSON keys must be strings.json.loads(): When deserializing,"null"remains a string key; it's not converted back toNone.
Avoid using None as a dictionary key. It leads to inconsistent behavior between Python and JSON.