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.

'{"website":"codespeedy","topic":"json and python","year":2019,"list":[10,20,30]}'

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='{"website":"codespeedy","topic":"json and python","year":2020,"list":[10,20,30]}'
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='{"website":"codespeedy","topic":"json and python","year":2020,"list":[10,20,30]}'
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

That’s all…

You can also learn:

Leave a Reply

Your email address will not be published.