PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
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 | 18 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")Code language: Python (python)

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")Code language: Python (python)

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'))Code language: Python (python)

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'])Code language: Python (python)

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'])Code language: Python (python)

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)Code language: Python (python)

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, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python JSON

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. zulu24 says

    June 10, 2024 at 11:37 am

    Thank you! This is the best article I have found on this. I last programmed a Python application using this logic about 2 years ago, so I needed a reminder on the syntax. I will also say that “short” if statements can be used as well, and that is what I used previously to reduce number of lines of code.

    Reply
  2. Indhu says

    June 22, 2022 at 8:04 pm

    Original = {
        "SampleRecord": {
            "SampleRules": [{
                "family_min_samples_percentage": 5,
                "original_number_of_clusters": 4,
                "Results": [{
                    "eps_value": 0.1,
                    "min_samples": 5,
                    "scores": {
                        "adjusted_rand_index": 0.001,
                        "adjusted mutual_info_score": 0.009
                    }
                }
                ],
                "Results2": [{
                    "min_samples": 5,
                    "scores": {
                        "adjusted_rand_index": 0.001,
                        "adjusted mutual_info_score": 0.009
                    }
                }
                ],
                "isnegative": "False",
                "action": "Allow",
                "comment": [
                    "@Comment"
                ]  #AttributeError: 'str' object has no attribute 'items'
            }
            ]
        }
    }

    How to access min_samples and comment?

    I have tried Original["SampleRecord"]["SampleRules"]["Results"]["min_samples"] but it throws keyError ["SampleRules"]

    Reply
  3. joe says

    May 27, 2022 at 5:06 pm

    this is joke right? You are assuming the structure is known. This is almost never the case.

    Reply
    • Joe Johnson says

      June 25, 2023 at 2:54 pm

      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.

      Reply
  4. nimaj says

    March 22, 2022 at 8:09 pm

    I extracted JSON data from an API but could not always rely on the structure. This helped me so fast! Thank you much!

    Reply
  5. Sakibur Rahman says

    January 5, 2022 at 2:34 am

    How to change json file value ?

    Reply
  6. Keerthi says

    August 22, 2021 at 7:25 pm

    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:

    Directory : hosts
    Subfolder1 : hostDev
    Json Files : dev.json, qa.json
    Subfolder2: hostQA
    Json Files : dev.json, qa.json

    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!

    Reply
  7. RalfF says

    July 19, 2021 at 8:46 pm

    Very useful. Thanks, man.

    Reply
    • Vishal says

      July 25, 2021 at 6:09 pm

      You’re welcome

      Reply
  8. betsy mcintosh says

    July 6, 2021 at 7:51 pm

    I believe I am close but need some help, how do I get the value of the “email” in the following json

    {
             "data": {
            "type": "registration_sets",
            "attributes": {
                "registrations": [
                    {"rule_set": "user_rule_set","first_name":"Bob","last_name":"Jones","email":"someemail@gmail.com","sso_id":"1234","student_id":"4321","location_id":"1111"
                           },
                    {
                        "rule_set": "he_learner",
                        "role": "undergrad"
                    }
                ]
            }
            }
            }
    Reply
    • Bryon says

      July 24, 2021 at 6:13 am

      This worked for me:

      import json
      
      someJSON='''{
        "data": {
          "type": "registration_sets",
          "attributes": {
            "registrations": [
              {
                "rule_set": "user_rule_set",
                "first_name": "Bob",
                "last_name": "Jones",
                "email": "someemail@gmail.com",
                "sso_id": "1234",
                "student_id": "4321",
                "location_id": "1111"
              },
              {
                "rule_set": "he_learner",
                "role": "undergrad"
              }
            ]
          }
        }
      }'''
      
      sampleDict=json.loads(someJSON)
      
      print sampleDict['data']['attributes']['registrations'][0]['email']

      “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.

      Reply
  9. Nilesh Yeole says

    December 17, 2020 at 2:06 pm

    This is really good stuff Vishal.
    Thank you

    Reply
    • Vishal says

      December 17, 2020 at 9:37 pm

      Thank you, Nilesh.

      Reply
  10. Brian says

    August 25, 2020 at 7:48 am

    Isn’t it faster to do try accept

    Reply
    • Brian says

      August 25, 2020 at 8:09 am

      except*

      Reply
  11. Rodrigo says

    August 9, 2020 at 6:15 am

    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?

    Reply
  12. Rumei Ma says

    May 12, 2020 at 7:32 pm

    Very helpful article about JSON and Python. Thanks

    Reply
    • Vishal says

      May 14, 2020 at 4:56 pm

      You’re welcome Rumei Ma

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

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

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview 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.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com