Check If Python Json Object is Empty (original) (raw)
Last Updated : 25 Apr, 2024
Python users frequently work with JSON, particularly when exchanging data between multiple devices. In this article, we'll learn how to check if a JSON object is empty using Python.
Check If a JSON Object Is Empty in Python
Below, we provide examples to illustrate how to check if a JSON object is empty or not using Python.
- Using len() function
- Using not operator
- Using Empty Dictionary Comparision
Check If a JSON Object Is Empty Using len() Method
In this example, below code defines a function `is_json_empty` that takes a JSON object as input and returns `True` if its length is 0, indicating an empty JSON object. It then creates an empty JSON object, `json_obj`, and prints the result of calling the function.
Python3 `
import json
def is_json_empty(json_obj): # return true if length is 0. return len(json_obj) == 0
json_obj = {} # Empty JSON object print(is_json_empty(json_obj))
`
Check If a JSON Object Is Empty Using not Operator
In this example, belowcode checks if two JSON objects, `Geeks` (empty) and `GeeksTutorial` (with data), are empty and prints the corresponding messages. In this instance, it prints "JSON object 1 is empty." for `Geeks` and "JSON object 2 is not empty." along with the contents of `GeeksTutorial`.
Python3 `
JSON object 1
Geeks = {}
JSON object 2
GeeksTutorial = { "title": "Introduction to Python", "author": "GeeksforGeeks", "topics": ["Basics", "Data Structures", "Functions", "Modules"], }
Check if the JSON object is empty
if not Geeks: print("JSON object 1 is empty.") else: print("JSON object 1 is not empty.")
Check if the JSON object is empty
if not GeeksTutorial: print("JSON object 2 is empty.") else: print("JSON object 2 is not empty.") print(GeeksTutorial)
`
Output
JSON object 1 is empty. JSON object 2 is not empty. {'title': 'Introduction to Python', 'author': 'GeeksforGeeks', 'topics': ['Basics', 'Data Structures', 'Functions', 'Modules']}
Check If a JSON Object Is Empty Using Comparision
In this example, code defines a function `is_json_empty` that checks if a JSON object is empty by comparing it to an empty dictionary (`{}`). It then creates an empty JSON object, `json_obj`, and prints the result of calling the function with this object, confirming that the output is `True`.
Python3 `
import json
def is_json_empty(json_obj): return json_obj == {}
json_obj = {} # Empty JSON object print(is_json_empty(json_obj))
`
Conclusion
In this article, we explored three different methods to check if a JSON object is empty in Python. Whether you prefer using the len() function, the not operator, or directly comparing the JSON object with an empty dictionary, you have multiple options to accomplish this task efficiently.