Software Development and QA Tips

How to Handle Null in JSON Object in Python

Written by QASource Engineering Team | Sep 23, 2024 4:00:00 PM

Although JSON was originally based on JavaScript, its syntax is similar to that of Python dictionaries. In JSON, the NULL value is represented by the keyword "null", while in Python, the NULL is equivalent to the None keyword.

To manage null values in JSON using the Jackson library in Java, follow these steps:

  1. Add Jackson Dependency
    • Open your pom.xml file
    • Add the Jackson Library as a dependency to your project
  2. Import Jackson Annotations
    • In your Java class, import the required annotations from the Jackson library
  3. Apply the @JsonInclude Annotation
    • Use the @JsonInclude annotation with the Include.NON_NULL option on your class or specific fields to exclude null values from the JSON output

Example of Excluding Null Values from JSON Output

The fields with null values are removed in the example below, resulting in a cleaner JSON output.

Before:
{
"name" :"Sanitizer",
"productNo": null,
"targetArea" : null,
"SellingPrice":0.0
}
After using "@JsonInclude(value=Include.Non_Null)"
{
"name": "Sanitizer",
"SellingPrice":0.0
}

Handling null values effectively in JSON is crucial for producing clean and efficient data. Whether using Python or Java, methods can exclude these values from your JSON responses.