Check if Json Object Has Empty Value in Python

JSON is a data format available across platforms allowing the interchange of data in human-readable form. It stands for JavaScript Object Notation (JSON).

Python has a library called “json” that is used when working with JSON. JSON format works just like Python Dictionary except for the following value conversions:

Python data typesJSON Equivalent
Truetrue
Falsefalse
floatNumber
intNumber
Nonenull
dictObject
listArray
tupleArray
Table 1: Conversions that happen when you convert a Python datatype to JSON format.

Python dictionary is key-value data format and is generally presented in code as follows:

{<key1>:<value1>, <key2>:<value2>, …}

Before we go into how to check for empty values, we must understand how to convert Python dictionary to JSON and vice-versa using json package.

Converting Python dictionary into JSON

This is done using the dumps() function in json package as follows

import json
# A python dictionary
products = {
	"product1": {
    	"price": 45,
    	"name" : "glasses 6B",
    	"types" : ["A", "B"],
    	"manufacturer": None,
    	"approved": True,
    	"category": 67
    	},
	"product2": {
    	"price": 45,
    	"name" : "dress 1XB",
    	"types" : ["X", "B"],
    	"manufacturer": "ABC textile",
    	"approved": False,
    	"category": 23
    	},
	"product3": {
    	"price": None,
    	"name" : "boots",
    	"types" : [],
    	"manufacturer": "XYZ wears",
    	"approved": True,
    	"category": " "
    	}
}
#converting Python dictionary into JSON data fromat
obj = json.dumps(products, indent=3)
# printing the JSON data
print(obj)
print("type obj: ", type(obj))

Output (truncated):

{
   "product1": {
  	"price": 45,
  	"name": "glasses 6B",
  	"types": [
     	"A",
     	"B"
  	],
  	"manufacturer": null,
  	"approved": true,
  	"category": 67
   },
…
type obj:  <class 'str'>

As expected, when the above code is executed, the Python dictionary products convert into an Object (see Table 1). Other values were also converted accordingly, for example, None to null.

Converting JSON string into Python dictionary

JSON data can be converted into a Python dictionary using the loads() function in json. For example:

import json
student = '{"Name": "Smith","Reg":2719, "Grade": 2}'
print(type(student))
student_json = json.loads(student)
print(student_json)
print(type(student_json))

Output:

<class 'str'>
{'Name': 'Smith', 'Reg': 2719, 'Grade': 2}
<class 'dict'>

The function json.loads() as converted the string “student” into a dictionary “student_json”. For this kind of json conversion,  ensure you use double quotes inside the string; otherwise, the conversion will fail. Alternatively, you can use the literal_eval function in ast module to convert a string into a Python dictionary as follows

from ast import literal_eval
student_json = literal_eval(student)

Check if JSON has an Empty Value

Suppose we want to look for products with empty values in some keys. Remember that you need to convert JSON data into a Python dictionary before using it as a regular dictionary. This is because JSON data format is of string (<str>) datatype in Python. For this reason, we will work with a Python dictionary to check for empty values.

Empty values can occur in different forms depending on the context, for example, using None, an empty string (” “), an empty list ([ ]) or tuple, or even the value False. Let’s see an example.

import json
# Python dictionary
products = {
	"product1": {
    	"price": 45,
    	"name" : "glasses 6B",
    	"types" : ["A", "B"],
    	"manufacturer": None,
    	"approved": True,
    	"category": 67
    	},
	"product2": {
    	"price": "",
    	"name" : "dress 1XB",
    	"types" : ["X", "B"],
    	"manufacturer": "ABC textile",
    	"approved": False,
    	"category": 23
    	},
	"product3": {
    	"price": None,
    	"name" : "boots",
    	"types" : [],
    	"manufacturer": "XYZ wears",
    	"approved": True,
    	"category": ""
    	}
}
# converting Python dictionary into JSON data format
obj = json.dumps(products, indent=3)

# Looping through products to check products with no product value
for product in products:
	# price indicated as "", [], None, 0 or False is considered missing
	if products[product]["price"] in ("", [], None, 0, False):
    		print("No price value in: ", product)
	else:
    		print("Price value indicated: ", product)

Output:

Price value indicated:  product1
No price value in:  product2
No price value in:  product3

In the above code, we defined the Python products dictionary and converted it into JSON format obj  using json.dumps(), but when looping through the products we use the dictionary and not JSON because JSON is of string data type, as we said earlier. We did not have to convert the Python dictionary to JSON in this case. If you have JSON at the beginning, you need to convert it to a Python dictionary to work with it.

If you want to check if any or all of the products have price values, then you can use any and all inbuilt functions in python as follows:

a = any([products[product]["price"] in ("", [], None, 0, False) for product in products])
print(a)

Output:

True
b = all([products[product]["price"] in ("", [], None, 0, False) for product in products])
print(b)

Output:

False