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

Python to check existence of nested JSON key-value - Stack Overflow
I have JSON in given format and my goal is to determine if the key-value pair of "name" : "Important1", "name" : "Important2", "name" : "Impor... More on stackoverflow.com
🌐 stackoverflow.com
python - Elegant way to check if a nested key exists in a dict? - Stack Overflow
Is there are more readable way to check if a key buried in a dict exists without checking each level independently? Lets say I need to get this value in a object buried (example taken from Wikidat... More on stackoverflow.com
🌐 stackoverflow.com
How to check if something is in a JSON object before running if statement
There's no such thing as a "JSON object." There's a JSON string, which represents an object, but once you've deserialized the string you're holding a regular Python dictionary or list. So all of the regular Python membership tests work - you test whether the collection contains a key or a value by using in. 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. if "subtitle" not in record or record["subtitle"] != "French": add_french_subtitles(record) # or whatever More on reddit.com
🌐 r/learnpython
11
6
September 15, 2023
Check if key exists and iterate the JSON array using Python - Stack Overflow
This expression really helped, couldn't find it elsewhere... Lol. Thanks 5 years later! data.get(attribute) or default_value in this case is the same as data[attribute], but doesn't throw KeyError if the key doesn't exist. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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 ...
🌐
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.
Find elsewhere
🌐
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.
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.

🌐
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 

🌐
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.
🌐
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.
🌐
CopyProgramming
copyprogramming.com › howto › check-if-json-has-key-python
Check if json has key python
December 20, 2025 - This guide covers the essential methods to check if a JSON key is true, whether a key exists in JSON, and the latest best practices for 2026, including Python 3.13+ features and modern validation libraries. The standard Python json module converts JSON data into Python dictionaries, where keys become string identifiers and values include booleans, numbers, strings, and nested structures.
🌐
Python.org
discuss.python.org › python help
How to Check if key Error key exist in a JSON String Python - Python Help - Discussions on Python.org
September 24, 2022 - If i want to check if my JSON String contain Error from API request, i have a string that saved the respond, Example final = response.json() And i want to check if the API response error
🌐
HatchJS
hatchjs.com › home › how to check if a key exists in a json object in python
How to Check if a Key Exists in a JSON Object in Python
January 5, 2024 - python if “name” in data: print(“The key ‘name’ exists in the JSON object.”) else: print(“The key ‘name’ does not exist in the JSON object.”) Q: What if the key I’m looking for is nested inside another object?