This is an old question with accepted answer, but I would do this using nested if statements instead.

import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if 'A' in json:
    if 'B' in json['A']:
        if 'C' in json['A']['B']:
            print(json['A']['B']['C']) #or whatever you want to do

or if you know that you always have 'A' and 'B':

import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if 'C' in json['A']['B']:
    print(json['A']['B']['C']) #or whatever
Answer from Daniel Zakrisson on Stack Overflow
🌐
PYnative
pynative.com › 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
May 14, 2021 - Check if the key exists or not in JSON using Python. Check if there is a value for a key. Return default value if the key is missing in JSON. Iterate JSON array in Python.
🌐
Reddit
reddit.com › r/learnpython › how to check if nested json has key/value pair when when subcategory names are not consistent.
r/learnpython on Reddit: How to check if nested json has key/value pair when when subcategory names are not consistent.
April 3, 2022 -

I have the following json structure file:

parent1
-------subcat1
----------------subsubcat1
----------------....
----------------subsubcatN
-------....
-------subcatN

parent2
-------subcat1
----------------subsubcat1
----------------....
----------------subsubcatN
-------....
-------subcatN

and each subsubcat has list of dictionaries in which one key - value pair can be 'uid':'12563'.

I need to check if parent1, parent2 has this par, or none of them... problem i subcat and subsubcat keys are not consistent (they change depending on json file), deepness stays the same.

Basically i need smng like

if json['parent1][*][*][*]['uid']  == 12563

but it's not gonna work :)

🌐
CopyProgramming
copyprogramming.com › howto › check-if-key-exists-and-iterate-the-json-array-using-python
Python JSON: How to Check if Key Exists, Iterate Arrays, and Apply 2026 Best Practices
November 2, 2025 - The in operator is the most efficient and Pythonic method to check key existence in a JSON object. This approach returns True if the key is present and False otherwise, without throwing exceptions.
🌐
Reddit
reddit.com › r/learnpython › how to check if something is in a json object before running if statement
r/learnpython on Reddit: How to check if something is in a JSON object before running if statement
September 15, 2023 -

Ok... This is a little complicated... So... Sorry in advance

I have a function that returns attributes of a video file (FFprobe) in a JSON object, and then a little factory that parses the JSON looking for specific attributes, and running if statements on those attributes.

I.E. One of attributes in the JSON is subtitle format. So if the subtitle format != a desired format, then set a variable that is used in another format for encoding the subtitle to the desired format

The issue that I have run into so that sometimes those attributes (like subtitle) don't exist in the JSON because they do not exist in the file.

So I sort of need to check if the attribute in the JSON exists, before I check to see if if that attribute is the desired attribute and start setting variables

How do I do this?

Would it be as simple as:

json_object= json.loads(studentJson)
if "subtitle_format" in json_object: 
    print("Key exist in json_object") 
    print(subtitle_format["ASS"], " is the subtitle format") 
else: 
    print("Key doesn't exist in JSON data")

If yes, would I get yelled at if the if statement had a few layers? Psudo:

if subtitle_format in json_object:
    if subtitle_format == ass
         if subtitle_format == english
             encode 

🌐
Stack Overflow
stackoverflow.com › questions › 67818737 › python-to-check-existence-of-nested-json-key-value
Python to check existence of nested JSON key-value - Stack Overflow
def keys_exists(element, *keys): """ Check if *keys (nested) exists in `element` (dict). """ if type(element) is not dict: raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise AttributeError('keys_exists() ...
🌐
LabEx
labex.io › tutorials › python-how-to-handle-keyerror-when-accessing-nested-keys-in-a-python-json-object-395073
How to handle KeyError when accessing nested keys in a Python JSON object | LabEx
Using dict.get() method: Zip code: ... information: User John Doe lives in Anytown, CA Unknown Primary hobby: reading · The deep_get() function we created provides a robust way to access nested values in a dictionary without raising ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-check-if-nested-key-exists-in-dictionary
Check if a nested key exists in a Dictionary in Python | bobbyhadz
Copied!my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu' } } try: city = my_dict['address']['city'] print(city) # 👉️ Oulu except KeyError: print('The specified key does NOT exist') # ------------------------------------------------- try: result = my_dict['not']['found']['key'] except KeyError: # 👇️ this runs print('The specified key does NOT exist') ... We try to access a nested key in the try block of the try/except statement. If one of the keys doesn't exist, a KeyError exception is raised and is then handled by the except block.
Find elsewhere
Top answer
1 of 16
249

To be brief, with Python you must trust it is easier to ask for forgiveness than permission

try:
    x = s['mainsnak']['datavalue']['value']['numeric-id']
except KeyError:
    pass

The answer

Here is how I deal with nested dict keys:

def keys_exists(element, *keys):
    '''
    Check if *keys (nested) exists in `element` (dict).
    '''
    if not isinstance(element, dict):
        raise AttributeError('keys_exists() expects dict as first argument.')
    if len(keys) == 0:
        raise AttributeError('keys_exists() expects at least two arguments, one given.')

    _element = element
    for key in keys:
        try:
            _element = _element[key]
        except KeyError:
            return False
    return True

Example:

data = {
    "spam": {
        "egg": {
            "bacon": "Well..",
            "sausages": "Spam egg sausages and spam",
            "spam": "does not have much spam in it"
        }
    }
}

print 'spam (exists): {}'.format(keys_exists(data, "spam"))
print 'spam > bacon (do not exists): {}'.format(keys_exists(data, "spam", "bacon"))
print 'spam > egg (exists): {}'.format(keys_exists(data, "spam", "egg"))
print 'spam > egg > bacon (exists): {}'.format(keys_exists(data, "spam", "egg", "bacon"))

Output:

spam (exists): True
spam > bacon (do not exists): False
spam > egg (exists): True
spam > egg > bacon (exists): True

It loop in given element testing each key in given order.

I prefere this to all variable.get('key', {}) methods I found because it follows EAFP.

Function except to be called like: keys_exists(dict_element_to_test, 'key_level_0', 'key_level_1', 'key_level_n', ..). At least two arguments are required, the element and one key, but you can add how many keys you want.

If you need to use kind of map, you can do something like:

expected_keys = ['spam', 'egg', 'bacon']
keys_exists(data, *expected_keys)
2 of 16
36

You could use .get with defaults:

s.get('mainsnak', {}).get('datavalue', {}).get('value', {}).get('numeric-id')

but this is almost certainly less clear than using try/except.

🌐
sqlpey
sqlpey.com › python › solved-how-to-check-if-key-exists-and-iterate-json-array-using-python
Solved: How to Check if a Key Exists and Iterate a JSON Array in Python
November 6, 2024 - A: You can use the in keyword to check for key existence in a dictionary or use the get() method for safer retrieval, returning a default value if the key is missing.
🌐
Claudia Kuenzler
claudiokuenzler.com › blog › 1395 › how-to-iterate-nested-json-dict-search-specific-value-print-key-python
How to iterate through a nested JSON, search for a specific value and print the key with Python
February 27, 2024 - If a specific key is not found but a nested JSON exists, run the same function again with the nested JSON - a loop within a loop until either the wanted JSON key is found or the nested JSON data has ended.
🌐
Iditect
iditect.com › program-example › check-if-key-exists-and-iterate-the-json-array-using-python.html
Check if key exists and iterate the JSON array using Python
Description: This query explains how to iterate over an array within a JSON object in Python. import json data = '{"people": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}' json_data = json.loads(data) for person in json_data['people']: print(f"Name: {person['name']}, Age: {person['age']}") ... Description: This query covers how to check if a key exists in a nested JSON object.
🌐
FreeKB
freekb.net › Article
Python (Scripting) - Determine if JSON key exists
December 26, 2023 - #!/usr/bin/python3 import json raw_json = '{ "foo": "Hello World" }' try: parsed_json = json.loads(raw_json) except Exception as exception: print(f"Got the following exception: {exception}") if 'bar' not in parsed_json: print("The bar key does not exist") Let's say you have nested JSON, like this.
🌐
CodeSpeedy
codespeedy.com › home › check if a key exists in a json string or not in python
Check if a Key Exists in a JSON String or not in Python - CodeSpeedy
January 3, 2020 - 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")
🌐
Zditect
zditect.com › blog › 55408438.html
python json check if value exists
We cannot provide a description for this page right now
🌐
Medium
perfecto25.medium.com › python-dictionaries-get-nested-value-the-sane-way-4052ab99356b
Python Dictor — get a Dictionary/JSON nested value the sane way | by Mike R | Medium
September 16, 2019 - And you don’t want to write constant try/except blocks for every value you need to get from the Dictionary or the JSON? Here’s a simple function to handle all these scenarios. If there is any form of error, the function returns the value of None, or a custom specify a custom default value · Now try to get a value from the sample Dict above, age_minimum = dictor(data, "properties.age.minimum") ... Heres a fake key that doesnt exist, the value returned is None, no messy Key or Index or Value errors,
🌐
pythontutorials
pythontutorials.net › blog › check-if-key-exists-and-iterate-the-json-array-using-python
How to Check if a Key Exists and Iterate a JSON Array in Python (Semi-Structured Data Example) — pythontutorials.net
For fields that may be missing (e.g., address, phone), get() is cleaner than in checks for nested access. Use libraries like pydantic (for schema validation) or manual checks to ensure data types match expectations (e.g., isinstance(user, dict)). For critical workflows, use try-except to catch errors and log them (e.g., "User 5 has invalid contact data: not a dict"). Working with semi-structured JSON in Python requires two core skills: checking for key existence and iterating over arrays.