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:
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
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.
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.
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.
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.
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.
Indhu says
How to access min_samples and comment?
I have tried
Original["SampleRecord"]["SampleRules"]["Results"]["min_samples"]
but it throwskeyError ["SampleRules"]
joe says
this is joke right? You are assuming the structure is known. This is almost never the case.
Joe Johnson says
Actually, that’s not true at all. In a majority of cases, JSON has now replaced XML as the defacto message exchange format for business transactions. As such, and as with XML DTD usage, the format is authored and adhered to through published public APIs with documented message formatting. Or, simply exchanging such information between business entities. While it’s not as formal as XML once was, you should easily know the format for most 3rd-party JSON messages through their APIs and documented web services.
nimaj says
I extracted JSON data from an API but could not always rely on the structure. This helped me so fast! Thank you much!
Sakibur Rahman says
How to change json file value ?
Keerthi says
Hello Vishal,
I have a requirement to read all the json files inside all the subfolders of a single directory and iterate through the json array in all the json files and put the json values alone line by line separated by delimiter ‘;’ into a single text file. Could you guide me on how can I achieve this in Python?
For example:
read all the json from all the json files from hostDev and hostQA and keep the json values all together in a single text file like below line by line:
dev.json : {key1:val2,key2:val2,key3:val3}
,qa.json: {key1:val2,key2:val2,key3:val3}
sample.text:
val1;val2;val3
val1;val2;val3
val1;val2;val3
Appreciate your help. Thanks in advance!
RalfF says
Very useful. Thanks, man.
Vishal says
You’re welcome
betsy mcintosh says
I believe I am close but need some help, how do I get the value of the “email” in the following json
Bryon says
This worked for me:
“registrations” is a list of objects, so you need to reference a given object inside the list by its index instead of by some key name.
Nilesh Yeole says
This is really good stuff Vishal.
Thank you
Vishal says
Thank you, Nilesh.
Brian says
Isn’t it faster to do try accept
Brian says
except*
Rodrigo says
Hello on my Json I have a key called
{license: invalid}
I would like to do a check with python and find out if the value of the key “license” is equal to “valid” if it is “invalid” it returns a command.
How do I run this code?
Rumei Ma says
Very helpful article about JSON and Python. Thanks
Vishal says
You’re welcome Rumei Ma