In this article, we will see how to perform the following JSON operations using Python.
- Check if the key exists or not in JSON
- Check if there is a value for a key, and return a default value if the key is missing
- Iterate JSON array
Let’s see each one by one.
Further Reading:
- Solve Python JSON Exercise to practice Python JSON skills
Check if the key exists or not in JSON
Let’s assume you received the following student, JSON. And you wanted to check if the percentage key is present or not in JSON data. if it is present directly to access its value instead of iterating the entire JSON.
student ={ "id":1, "name":"john wick", "class":8, "percentage":75, "email":"jhon@pynative.com" }
Example:
import json
studentJson ="""{
"id": 1,
"name": "john wick",
"class": 8,
"percentage": 75,
"email": "jhon@pynative.com"
}"""
print("Checking if percentage key exists in JSON")
student = json.loads(studentJson)
if "percentage" in student:
print("Key exist in JSON data")
print(student["name"], "marks is: ", student["percentage"])
else:
print("Key doesn't exist in JSON data")
Output:
Checking if percentage key exists in JSON Key exist in JSON data john wick marks is: 75
Note: We used json.loads()
method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.
Check if there is a value for a key in JSON
We need a value of the key to be present in JSON so we can use this value in our system. In this case, we need to be sure that value is present for a key, and if it is none or not present, we use the default value.
Example to check if there is a value for a key in JSON
import json
studentJson ="""{
"id": 1,
"name": "john wick",
"class": null,
"percentage": 75,
"email": "jhon@pynative.com"
}"""
student = json.loads(studentJson)
if not (student.get('email') is None):
print("value is present for given JSON key")
print(student.get('email'))
else:
print("value is not present for given JSON key")
Output:
value is present for given JSON key jhon@pynative.com
Return default value if the key is missing
Let’s see how to use a default value if the value is not present for a key. As you know, the json.loads
method converts JSON data into Python dict
so we can use the get method of dict
class to assign a default value to the key if the value is missing.
import json
studentJson ="""{
"id": 1,
"name": "john wick",
"class": null,
"percentage": 75,
"email": "jhon@pynative.com"
}"""
student = json.loads(studentJson)
if not (student.get('subject') is None):
print("value is present for given JSON key")
print(student.get('subject'))
else:
print("using a default value for a given key")
print(student.get('subject', 'Science'))
Output
value is not present for given JSON key using a default value for a given key Science
Python Find if the nested key exists in JSON
Most of the time, JSON contains so many nested keys. Let’s see how to access nested key-value pairs from JSON directly. Let’s assume you have the following JSON data. and you want to check and access the value of nested key marks.
{ "class":{ "student":{ "name":"jhon", "marks":{ "physics":70, "mathematics":80 } } } }
Example 1: Access nested key directly
If you know that you always have the parent key present, then you can access the nested JSON key directly. In this case, we always have ‘class‘ and ‘student‘ keys so we can access nested key marks directly.
import json
sampleJson = """{
"class":{
"student":{
"name":"jhon",
"marks":{
"physics":70,
"mathematics":80
}
}
}
}"""
print("Checking if nested JSON key exists or not")
sampleDict = json.loads(sampleJson)
if 'marks' in sampleDict['class']['student']:
print("Student Marks are")
print("Printing nested JSON key directly")
print(sampleDict['class']['student']['marks'])
Output
Checking if nested JSON key exists or not Student Marks are Printing nested JSON key directly {'physics': 70, 'mathematics': 80}
Example 2: Access nested key using nested if
statement
If you are not sure whether you always have the parent key present, in such cases, we need to access nested JSON using nested if statement, to avoid any exceptions.
import json
sampleJson = """{
"class":{
"student":{
"name":"jhon",
"marks":{
"physics": 70,
"mathematics": 80
}
}
}
}"""
print("Checking if nested JSON key exists or not")
sampleDict = json.loads(sampleJson)
if 'class' in sampleDict:
if 'student' in sampleDict['class']:
if 'marks' in sampleDict['class']['student']:
print("Printing nested JSON key-value")
print(sampleDict['class']['student']['marks'])
Iterate JSON Array
Many times nested JSON key contains a value in the form of an array or dictionary. In this case, if you need all values, we can iterate the nested JSON array. Let’s see the example.
import json
sampleJson = """{
"class":{
"student":{
"name":"jhon",
"marks":{
"physics": 70,
"mathematics": 80
},
"subjects": ["sub1", "sub2", "sub3", "sub4"]
}
}
}"""
sampleDict = json.loads(sampleJson)
if 'class' in sampleDict:
if 'student' in sampleDict['class']:
if 'subjects' in sampleDict['class']['student']:
print("Iterating JSON array")
for sub in sampleDict['class']['student']['subjects']:
print(sub)
Output:
Iterating JSON array sub1 sub2 sub3 sub4
So What Do You Think?
I want to hear from you. What do you think of this article? Let me know by leaving a comment below.
Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.