This might help you.

def func1(data):
    for key,value in data.items():
        print (str(key)+'->'+str(value))
        if type(value) == type(dict()):
            func1(value)
        elif type(value) == type(list()):
            for val in value:
                if type(val) == type(str()):
                    pass
                elif type(val) == type(list()):
                    pass
                else:
                    func1(val)
func1(data)

All you have to do is to pass the JSON Object as Dictionary to the Function.

There is also this python library that might help you with this.You can find this here -> JsonJ

PEACE BRO!!!

Answer from Joish on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-through-nested-json-object-using-python
Iterate Through Nested Json Object using Python - GeeksforGeeks
July 23, 2025 - In this example, the Python code defines a function, `iterate_nested_json_list_comprehension`, which utilizes list comprehension to recursively iterate through a nested JSON object, creating a list of tuples containing key-value pairs.
Discussions

python - Iterate through nested JSON object - Stack Overflow
How do I parse through JSON with unknown variables? I know "Europe" will always exist, but the city names (e.g. Germany, ...etc) will always be variable. I am trying to extract the city and hostn... More on stackoverflow.com
🌐 stackoverflow.com
How to Iterate through nested JSON in Python - Stack Overflow
I would like to find out how I can iterate through the Following JSON in Python 3 Specifically I would like to be able to pull out 'id' and 'lname'. My actual JSON file has about 300 entries { " More on stackoverflow.com
🌐 stackoverflow.com
Iterating nested json in python - Stack Overflow
To clarify: you already have a dictionary, and you want to print all the values, including values in nested dictionaries, but not the keys? What is the expected output for your example? ... I need to iterate through each key and value, replace all the values in the json with some other value. More on stackoverflow.com
🌐 stackoverflow.com
python - iterate through nested JSON - Stack Overflow
i'm trying to iterate in a json api respons and i'm unable to reach the data i need here is a api response example. "i know it 's not complete or valid json :)" { "status": "running", "reasons": ... More on stackoverflow.com
🌐 stackoverflow.com
September 1, 2017
🌐
Reddit
reddit.com › r/learnpython › best way to iterate through nested json?
r/learnpython on Reddit: Best way to iterate through nested JSON?
December 6, 2020 -

My Json is of the following format:

https://pastebin.com/KUKHHh2e

The numbers in this json are many as are the dates. I am trying to iterate through this to create a single list of dictionaries that contains all of the information in the dictionary that is 3 layers deep in the json.

I have made a loop that is n3 but it seems highly inefficient given i have around 30,000 iterations to make.

What are my options here?

🌐
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 - The first line (printing the full JSON) worked, but then the for loop failed miserably. The TypeError message doesn't make sense to a occasional Python script writer like me - but research revealed the reason behind the TypeError: we are trying to access a value using a key within another key and that’s leading to the occurrence of the error. The key is of the type string and not dict. In other words: Python is parsing through each component (from healthdetail).
🌐
Stack Overflow
stackoverflow.com › questions › 59368057 › how-to-iterate-through-nested-json-in-python
How to Iterate through nested JSON in Python - Stack Overflow
import json f = open('data1.json') data = json.load(f) f.close() for dataitems in data['datainfos']: print (dataitems['DataInfo']) Python returns a list, not a dictionary.
Find elsewhere
🌐
Quora
quora.com › How-do-I-loop-through-a-JSON-file-with-multiple-keys-sub-keys-in-Python
How to loop through a JSON file with multiple keys/sub-keys in Python - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
Restack
restack.io › p › nested-json-structure-examples-answer-iterate-through-nested-json-object-python
Where product teams design, test and optimize agents at Enterprise Scale — Restack
The open-source stack enabling product teams to improve their agent experience while engineers make them reliable at scale on Kubernetes.
Top answer
1 of 2
1

Here's the updated code with minimal changes, and it also fixes the issue while writing the JSONL file. The code in question would append a list of JSON to the file, which will make the file messier and hard to read through code.

import datetime
import json

ruletree = {
    "contract": "1234",
    "domainName": "www.domainA.com",
    "rules": {
        "name": "default",
        "children": [
            {
                "rule": "Rule1",
                "children": [],
                "behaviors": [
                    {
                        "name": "origin",
                        "options": {
                            "originType": "CUSTOMER",
                            "host": "gateway1.com",
                        },
                    }
                ],
            },
            {
                "rule": "Rule2",
                "children": [],
                "behaviors": [
                    {
                        "name": "origin",
                        "options": {
                            "originType": "CUSTOMER",
                            "host": "gateway2.com",
                        },
                    }
                ],
            },
        ],
    },
}

data = {
    'date_time': datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
    'domainName': ruletree['domainName'],
}

#code to get domainName, name & host
for rule in ruletree['rules']['children']:
    for behavior in rule['behaviors']:
        with open('domains.json', 'a+') as outfile: # writing to the file
            json.dump({
                **data,
                'rule': rule['rule'],
                'host': behavior['options']['host']
            }, outfile)
            outfile.write('\n')

File output:

{"date_time": "2023-07-11 11:28:21", "domainName": "www.domainA.com", "rule": "Rule1", "host": "gateway1.com"}
{"date_time": "2023-07-11 11:28:21", "domainName": "www.domainA.com", "rule": "Rule2", "host": "gateway2.com"}
2 of 2
1

A simple generator function will do here.

def get_rule_data(ruletree):
    for child in ruletree["rules"]["children"]:
        rule_name = child["rule"]
        for behavior in child.get("behaviors", []):
            try:
                host = behavior["options"]["host"]
                yield ruletree["domainName"], rule_name, host
            except KeyError:
                pass


now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

for domain, rule_name, origin_domain in get_rule_data(ruletree):
    print(
        {
            "date_time": now,
            "domainName": domain,
            "rule_name": rule_name,
            "host": origin_domain,
        }
    )
Top answer
1 of 2
2

Try:

def get_kv(o):
    if isinstance(o, dict):
        if "path" in o and "url" in o:
            yield o["path"], o["url"]
        for v in o.values():
            yield from get_kv(v)
    elif isinstance(o, list):
        for v in o:
            yield from get_kv(v)


print(dict(get_kv(data)))

Prints:

{
    "/1": "1_URL",
    "/12": "12_URL",
    "/123": "123_URL",
    "/13": "13_URL",
    "/131": "131_URL",
    "/1311": "1311_URL",
    "/13111": "13111_URL",
}
2 of 2
2

OK ... there is an excellent answer there by Andrej Kesely, so let's apply this answer to your json_extract function:

def json_extract(json_dct, key1, key2):
    dct   = {}
    def extract(json_dct, key1, key2):
        if isinstance(json_dct, dict):
            if key1 in json_dct and key2 in json_dct:
                dct[json_dct[key1]] = json_dct[key2]
            for v in json_dct.values():
                extract(v, key1, key2)
        elif isinstance(json_dct, list):
            for v in json_dct:
                extract(v, key1, key2)
        return dct
    result = extract(json_dct, key1, key2)
    return result

print(json_extract(data, "path", "url",))

And if you are curios how your way of approaching it could be turned into what you intended it to be without using the revelation that you have here to do with a dictionary from which all keys are available in parallel, check out:

def json_extract(obj, key, key2):
    stack = []
    dct   = {}
    def extract(obj, dct, stack, key, key2):
        if isinstance(obj, dict):
            for k, v in obj.items():
                if k == key2:
                    stack.append(v)
                if isinstance(v, (dict, list)):
                    extract(v, dct, stack, key, key2)
                elif k == key:
                    dct[stack.pop()] = v
        elif isinstance(obj, list):
            for item in obj:
                extract(item, dct, stack, key, key2)
        return dct
    result = extract(obj, dct, stack, key, key2)
    return result
🌐
PyPI
pypi.org › project › mo-json
mo-json · PyPI
path - a dot-delimited string specifying the path to the nested JSON. Use "." if your JSON starts with [, and is a list. expected_vars - a list of strings specifying the full property names required (all other properties are ignored) The most common use of parse() is to iterate over all the objects in a large, top-level, array: ... We will iterate through the array found on property a, and return both a and b variables.
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to flatten deeply nested json objects in non-recursive elegant python
How to Flatten Deeply Nested JSON Objects in Non-Recursive Elegant Python | Towards Data Science
March 5, 2025 - In the following example, "pets" is 2-level nested. The value for key "dolphin" is a list of dictionary. Loading the flattened results to a pandas data frame, we can get · The function "flatten_json_iterative_solution" solved the nested JSON problem with an iterative approach.
🌐
Reddit
reddit.com › r/learnpython › how do i loop through a nested object from a json file?
r/learnpython on Reddit: How do I loop through a nested object from a JSON file?
March 1, 2022 -

Hi there, I am trying to read through a package.json file which is below. I want to read in specifically the dependencies and add them to key, value variables. I can't figure out how to read in nested object. If anyone can give me any tips?

{
  "name": "untitled",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "express": "https://github.com/IAmAndyIE/expressjs.com.git"
  },
}

My current code is below.

import json


def test_document():
    f = open('../untitled/package.json')

    data = json.load(f)

    for key, values in data.items():
        if key == "dependencies":
            print(values)

    f.close()


if __name__ == '__main__':
    test_document()

Thanks

🌐
Medium
ankushkunwar7777.medium.com › get-data-from-large-nested-json-file-cf1146aa8c9e
Working With Large Nested JSON Data | by Ankush kunwar | Medium
January 8, 2023 - You can access the data in the ... from a nested JSON object using recursion, you can use a function that iterates through the object and extracts the desired values....
🌐
LabEx
labex.io › tutorials › python-how-to-efficiently-traverse-and-manipulate-nested-python-json-objects-395061
How to efficiently traverse and manipulate nested Python JSON objects | LabEx
Discover how to effectively navigate and manipulate complex nested JSON data structures in Python. Learn techniques to efficiently extract, update, and transform JSON objects for your Python applications.
🌐
Delft Stack
delftstack.com › home › howto › python › iterate through json python
How to Iterate Through JSON Object in Python | Delft Stack
February 2, 2024 - If it’s a dictionary, it iterates through the keys and values, prints them, and then recursively calls itself with the value. If it’s a list, the function iterates through the items and recursively calls itself for each item. The JSON string representing a person’s details, including nested address information, is loaded into a Python dictionary (json_data).