- Check if a Key Exists in a JSON String or not in Python
- Python Program to Check if a Key Exists in a JSON String
- Python Check if key exists in JSON and iterate the JSON array
- Check if the key exists or not in JSON
- Check if there is a value for a key in JSON
- Return default value if the key is missing
- Python Find if the nested key exists in JSON
- Iterate JSON Array
- So What Do You Think?
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Check if key exists and iterate the JSON array using Python
- How to check JSON key/object exist in python
- 3 Answers 3
Check if a Key Exists in a JSON String or not in Python
In this tutorial, we will learn how to check if a key exists in a JSON (JavaScript Object Notation) string or not using Python.
JSON is a popular and special type of data format used for data manipulation. So, let’s see…..
Python Program to Check if a Key Exists in a JSON String
First, let’s consider the following JSON string.
To detect whether a key exists in the above JSON formatted string or not, you should use the ‘in’ keyword as Python treats the above JSON data as String. See the below code and try to understand:
json_string='' if "website" in json_string: print("The required key is present") else: print("The required key is absent")
The output of the above program will be:
The required key is present
As the ‘website’ key is present in the json_string, so the ‘if’ block is executed.
We can not access the values using the keys in this method. To access the values you should convert the JSON string into a python dictionary by using ‘json.loads()’ method after importing the ‘json’ module. Then you can check whether a key exists in the dictionary or not and if it exists, you can access the value. See the following code.
import json json_string='' python_dict=json.loads(json_string) if "website" in python_dict: print("The required key is present") print("The value is="+str(python_dict["website"])) else: print("The required key is absent")
And below is the output result:
The required key is present The value is=codespeedy
Python Check if key exists in JSON and iterate the JSON array
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
Further Reading:
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.
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")
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")
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'))
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.
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'])
Checking if nested JSON key exists or not Student Marks are Printing nested JSON key directly
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)
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.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Check if key exists and iterate the JSON array using Python
Why do this explicit in checks and raise if they’re missing? Just access it without checking, and you’ll get exactly the same behavior (except with a KeyError instead of a ValueError ).
@abarnert because the question is about checking if a key exists or not. There might be something other than raising errors that OP wants to do.
If all you want is to check if key exists or not
If you want to check if there is a value for key
Return a default value if actual value is missing
It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.
For example create a helper method (or class JsonUtils with static methods) in json_utils.py :
def get_attribute(data, attribute, default_value): return data.get(attribute) or default_value
and then use it in your project:
from json_utils import get_attribute def my_cool_iteration_func(data): data_to = get_attribute(data, 'to', None) if not data_to: return data_to_data = get_attribute(data_to, 'data', []) for item in data_to_data: print('The id is: %s' % get_attribute(item, 'id', 'null'))
IMPORTANT NOTE:
There is a reason I am using data.get(attribute) or default_value instead of simply data.get(attribute, default_value) :
.get('my_key', 'nothing') # returns None .get('my_key') or 'nothing' # returns 'nothing'
In my applications getting attribute with value ‘null’ is the same as not getting the attribute at all. If your usage is different, you need to change this.
How to check JSON key/object exist in python
I’m very new to python. Is there anyway to check specific JSON object exist in python except my following code? Admit that my following code will not be good practice so need to know which way to better to check and easy to maintain? Here is JSON response:
[ < "MessageId": "250e37a8-d779-48a1-9941-84219a82513e", "ReceiptHandle": "AQEBjualXe2ywqTgIVmCNI5sKj7r48werf84HHA2BWZimwiEXLFxA/MiPBclK048NZBtOnM3dSDfoiwwqoNTPxTRz+IChd8McziweCxHX6texjAOi/MyAQjCWP+2hJPoxzQgXx9kjnKbepKlcgxhpOiQZe6WiSIq0dXwHHXSA7SP0g9NIR/dU38b+wmo0m2q7MNVfSct967EKF49wow9RHyFMO8iD8fH93PYT9om5NdUha3dvkWnisKcfuO5pZY3LLXPAnuZT/VfqxJjmPqb98iepBfqFb6SpM/02IVSql81XKJEbMBc4zPHp/Uace6e4UDGsn/hPCVsqQsTzrbKCR+ovpkhXipWwTYSlgsLe/o43k0UxhCN8eKhg835KuUkskA3T8C5Q6v6xgznlR7JJuhZpg==", "MD5OfBody": "bbdc5fdb8be7251f5c910905db994bab", "Body": "Information about current NY Times fiction bestseller for week of 12/11/2016.", "Attributes": < "SentTimestamp": "1553851566164" >, "MD5OfMessageAttributes": "d25a6aea97eb8f585bfa92d314504a92", "MessageAttributes": < "Author": < "StringValue": "John Grisham", "DataType": "String" >, "Title": < "StringValue": "The Whistler", "DataType": "String" >, "WeeksOn": < "StringValue": "6", "DataType": "Number" >> > ]
if 'Messages' in response: message = response['Messages'][0] receipt_handle = message['ReceiptHandle'] sqs.delete_message( QueueUrl=queue_url, ReceiptHandle=receipt_handle ) print('Received and deleted message: %s' % message) else: print('Message not received yet')
3 Answers 3
Another option that you can checkout and one that i actually prefer when i am using JSON data, is to create an object out of the JSON data and use the hasattr method. This will prevent that you start over-using try-except blocks and can also make your code more understandable. An example using your data is the following:
data= ''' < "MessageId": "250e37a8-d779-48a1-9941-84219a82513e", "ReceiptHandle": "AQEBjualXe2ywqTgIVmCNI5sKj7r48werf84HHA2BWZimwiEXLFxA/MiPBclK048NZBtOnM3dSDfoiwwqoNTPxTRz+IChd8McziweCxHX6texjAOi/MyAQjCWP+2hJPoxzQgXx9kjnKbepKlcgxhpOiQZe6WiSIq0dXwHHXSA7SP0g9NIR/dU38b+wmo0m2q7MNVfSct967EKF49wow9RHyFMO8iD8fH93PYT9om5NdUha3dvkWnisKcfuO5pZY3LLXPAnuZT/VfqxJjmPqb98iepBfqFb6SpM/02IVSql81XKJEbMBc4zPHp/Uace6e4UDGsn/hPCVsqQsTzrbKCR+ovpkhXipWwTYSlgsLe/o43k0UxhCN8eKhg835KuUkskA3T8C5Q6v6xgznlR7JJuhZpg==", "MD5OfBody": "bbdc5fdb8be7251f5c910905db994bab", "Body": "Information about current NY Times fiction bestseller for week of 12/11/2016.", "Attributes": , "MD5OfMessageAttributes": "d25a6aea97eb8f585bfa92d314504a92", "MessageAttributes": ,"Title": ,"WeeksOn": > > ''' import json class Response: def __init__(self, data): self.__dict__ = json.loads(data) response = Response(data) if hasattr(response , 'MessageId'): receipt_handle = response.ReceiptHandle print("Received and deleted message: %s" % response.MessageId) else: print('Message not received yet')
Received and deleted message: 250e37a8-d779-48a1-9941-84219a82513e
Could you please explain why MessageId is not interpreted as a dictionary key in your example? Thank you!
First as already mentioned you example json does not contain the key Messages . I think you code looks fine. But if the case that you have an json without the key Messages is very rare i would go for a try except block.
try: message = response['Messages'][0] receipt_handle = message['ReceiptHandle'] sqs.delete_message( QueueUrl=queue_url, ReceiptHandle=receipt_handle ) print('Received and deleted message: %s' % message) except KeyError: print('Message not received yet')
This will be much faster for every time you get an «correct» json. But slower when you are getting a json with a missing key. So maybe you need to find out weather the absence of the key occures often or not.
But this depends on the use case. And my answer is only my own opinion and experience from similar use cases
Since the response is a list of dict:
j_data = [, 'MD5OfMessageAttributes': 'd25a6aea97eb8f585bfa92d314504a92', 'MessageAttributes': , 'Title': , 'WeeksOn': >> ] for data in j_data: try: if 'MessageId' in data: message = data['MessageId'] receipt_handle = data['ReceiptHandle'] sentTimeStamp = data['Attributes']['SentTimestamp'] print(message) print(receipt_handle) print(sentTimeStamp) except KeyError: print("Some custom message here")
250e37a8-d779-48a1-9941-84219a82513e AQEBjualXJJuhZpg== 1553851566164
Another way could be to check for each key before accessing, i.e (removed the ReceiptHandle elem from the response):
j_data = [, 'MD5OfMessageAttributes': 'd25a6aea97eb8f585bfa92d314504a92', 'MessageAttributes': , 'Title': , 'WeeksOn': >> ] for data in j_data: try: if 'MessageId' in data: message = data['MessageId'] print(message) if 'ReceiptHandle' in data: receipt_handle = data['ReceiptHandle'] print(receipt_handle) if 'Attributes' in data: sentTimeStamp = data['Attributes']['SentTimestamp'] print(sentTimeStamp) except KeyError: print("Some custom message here")
250e37a8-d779-48a1-9941-84219a82513e 1553851566164