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()

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,

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:

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 strings using json.dumps() function.

Output:

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