Handle JSON NULL in Python

JavaScript Object Notation (JSON) is a lightweight data format used to exchange data across platforms. JSON data is of string type in Python.

Example

Here are some conversions made between JSON data and Python objects,

Table 1: Some changes made when a Python object is converted to JSON, and vice versa. Source: Author.

JSON string can be converted into a native Python object using json.loads() function. In doing so, JSON null values are converted to Python None. Conversely, a Python object can be converted into JSON formatted string using json.dumps().

Converting JSON to Python Object using json.loads()

import json
# JSON data string. Note that null is a valid JSON data type
# therefore, not enclosed with quotes
# JSON Keys must be enclosed with double quotes,
# meaning the entire string must be enclosed with
# single quotes or triple quotes.
json_string = '{"Name": "Smith", "Reg": null}'
print(type(json_string))
# Converting JSON data into Python object (dict)
dict_fromjson = json.loads(json_string)
print(type(dict_fromjson))
print(dict_fromjson)

Output:

<class 'str'>
<class 'dict'>
{'Name': 'Smith', 'Reg': None}

In the code snippet above, json.loads() method decoded JSON string into a Python dictionary (dict), effectively converting JSON null to Python None.

Here is another example,

Import json
json_string1 = """{"Name": "Alice", "Certificate": true, "Salary": 5600, "Reg": null}"""
dict_fromjson1 = json.loads(json_string1)
print(dict_fromjson1)

Output:

{'Name': 'Alice', 'Certificate': True, 'Salary': 5600, 'Reg': None}

As expected, when the JSON string is converted to a Python object, null changes to None, and true changes to True, as shown in Table 1.

Note: JSON properties (keys) must be enclosed in double quotes; otherwise, json.loads() will raise an error like this:

import json
json_string2 = """{'Name': 'Carol', 'Address': null }"""
dict_fromjson2 = json.loads(json_string2)
print(dict_fromjson2)

Output:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes:<loc>

Converting Python Object to JSON data

Python objects can be serialized into JSON string using json.dumps() function.

import json
# Python dictionary
dict1 = {"Name": "Bob", "Age": 42, "Address": None}
# Convert Python dictionary to JSON string
json_data1 = json.dumps(dict1)
print(type(dict1))
print(type(json_data1))
print(json_data1)

Output:

<class 'dict'>
<class 'str'>
{"Name": "Bob", "Age": 42, "Address": null}