In JavaScript, null represents the absence of a value. It means nothing. The Python equivalent to null is None.
When you parse the json data to Python objects, null becomes None. To handle the JSON null, you can use the json.loads() or json.load() method (when working with files).
import json # Example JSON string with null json_string = '{"name": "Calvin", "age": null, "country": "USA"}' # Parsing JSON string python_data = json.loads(json_string) print(python_data) # Output: {'name': 'Calvin', 'age': None, 'country': 'USA'}
You can see from the above output that null is automatically converted to None.
Serializing Python to JSON
If you have a Python object and want to serialize it to json, you can use the json.dumps() method. After converting to json values, None becomes null automatically.
import json python_dict = {"name": "Calvin", "age": None, "country": "USA"} # Parsing Python dictionary json_obj = json.dumps(python_dict) print(json_obj) # Output: {"name": "Calvin", "age": null, "country": "USA"}
Handling Non-Serializable Types (e.g., NaN)
JSON standard has no direct equivalent of Python’s NaN. However, you can still display a NaN value (along with Infinity and -Infinity if present) as it is in a JSON object by setting the allow_nan argument to True in the json.dumps() method.
import json import math data = {'value': math.nan} json_str = json.dumps(data, allow_nan=True) print(json_str) # Output: {"value": NaN}
And we get the NaN in the JSON standard.
Replacing null with Default Values
You need to define a custom function that accepts a Python object and a default value. Then convert all the None values to the default values.
import json def replace_none(obj, default): if isinstance(obj, dict): return {k: replace_none(v, default) for k, v in obj.items()} elif isinstance(obj, list): return [replace_none(elem, default) for elem in obj] return obj if obj is not None else default python_obj = json.loads('{"name": null}') processed = replace_none(python_obj, 'default') print(processed) # Output: {'name': 'default'}
In this code, first, we load the json data into a Python object using the json.loads() method.
In the next step, we passed that object to the custom replace_none() method. This custom method returns the “default” value instead of None values because we replaced the default with it.
That’s all!