Check if Json Object has Empty Value in Python
We have JSON data and we need to check if the JSON Object has an empty value or not in Python. In this article, we will see some methods that help us to check if JSON objects have empty values or not in Python.
Example
Input : '{"name": "John", "age": 25, "city": ""}'
Output : Empty Value Found for Key : City
Explanation: Here, we have JSON data, and we identify the city with an empty value.
How to Check If Json Object has Empty Value in Python
Below, are the methods of how to check if a JSON Object has an empty value in Python:
- Iterating JSON Keys and Values
- Using List Comprehension
- Using JSON path-ng Library
Check If Json Object Has Empty Value by Iterating JSON Keys and Values
In this example, below code imports, the `json` module, processes a JSON string (`,`) with key-value pairs, and converts it into a Python dictionary (`parsed_json`). It then iterates through the dictionary, identifying and printing keys linked to empty values like an empty string or null.
import json
json_data = '{"name": "John", "age": 25, "city": "", "email": null}'
parsed_json = json.loads(json_data)
for key, value in parsed_json.items():
if not value:
print(f"Empty value found for key: {key}")
Output
Empty value found for key: city Empty value found for key: email
Check If Json Object Has Empty Value Using List Comprehension
This Python code uses the json
module to parse a JSON string (json_data
) into a Python dictionary (parsed_json
). It then creates a list (empty_values
) to check for empty values in the dictionary. The result is determined using the any()
function.
import json
json_data = '{"name": "John", "age": 25, "city": "", "email": null}'
parsed_json = json.loads(json_data)
empty_values = [not value for value in parsed_json.values()]
result = any(empty_values)
print(f"Does the JSON object have empty values? {result}")
Output
Does the JSON object have empty values? True
Check If Json Object Has Empty Value Using jsonpath-ng Library
In this example, below code employs the json
and jsonpath_ng
modules to process a JSON string (json_data
). It loads the data into a Python dictionary (parsed_json
) and utilizes a JSONPath expression to find elements with null or empty values. The result is a boolean value indicating whether the JSON object contains such values,
import json
from jsonpath_ng import jsonpath, parse
json_data = '{"name": "John", "age": 25, "city": "", "email": null}'
parsed_json = json.loads(json_data)
# Using select with a lambda function for filtering
jsonpath_expr = parse("$..*").find(parsed_json)
matches = [match.value for match in jsonpath_expr if match.value == '' or match.value is None]
result = bool(matches)
print(f"Does the JSON object have empty values? {result}")
Output:
Does the JSON object have empty values? True