PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » JSON » Python Check if key exists in JSON and iterate the JSON array

Python Check if key exists in JSON and iterate the JSON array

Updated on: May 14, 2021 | 17 Comments

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.

Filed Under: Python, Python JSON

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

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 Python JSON

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
Exercises
Quizzes

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

[py_social-icons]

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Posted In

Python Python JSON
TweetF  sharein  shareP  Pin

  Python JSON

  • Python JSON Guide
  • JSON Serialization
  • JSON Parsing
  • JSON Validation
  • PrettyPrint JSON
  • Make Python Class JSON serializable
  • Convert JSON Into Custom Python Object
  • Python JSON Unicode
  • Parse JSON using Python requests
  • Post JSON using Python requests
  • Serialize DateTime into JSON
  • Serialize Python Set into JSON
  • Serialize NumPy array into JSON
  • Parse multiple JSON objects from file
  • Parse Nested JSON
  • Python JSON Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com