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 types | JSON Equivalent |
True | true |
False | false |
float | Number |
int | Number |
None | null |
dict | Object |
list | Array |
tuple | Array |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
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:
1 2 3 4 5 6 7 8 |
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
1 2 3 |
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 a tuple, or even the value False. Let’s see an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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:
1 2 |
a = any([products[product]["price"] in ("", [], None, 0, False) for product in products]) print(a) |
Output:
True
1 2 |
b = all([products[product]["price"] in ("", [], None, 0, False) for product in products]) print(b) |
Output:
False