I believe you probably meant:

from __future__ import print_function

for song in json_object:
    # now song is a dictionary
    for attribute, value in song.items():
        print(attribute, value) # example usage

NB: You could use song.iteritems instead of song.items if in Python 2.

Answer from tzot on Stack Overflow
🌐
Delft Stack
delftstack.com › home › howto › python › iterate through json python
How to Iterate Through JSON Object in Python | Delft Stack
February 2, 2024 - The essential part of this example is the for loop. Instead of using the more traditional approach of iterating through keys and accessing values separately, we employ the items() method.
🌐
freeCodeCamp
forum.freecodecamp.org › python
Help Iterate Python - Json file - Python - The freeCodeCamp Forum
November 28, 2020 - Can you help me iterate over this Json file ?to have the ‘name’ { “data”: [ { “circulating_supply”: 18556575, “cmc_rank”: 1, “date_added”: “2013-04-28T00:00:00.000Z”, “id”: 1, “last_updated”: “2020-11-28T10:13:02.000Z”, “max_supply”: 21000000, “name”: “Bitcoin”, “num_market_pairs”: 9550, “platform”: null, “quote”: { “USD”: { “last_updated”: “2020-11-28T10:13:02.000Z”, “market_cap”: 315363411475.37506, “percent_change_1h”: -0.09085874, “percent_change_24h”: -0.96244779, “percen...
🌐
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_for_loop`, which uses a for loop to recursively iterate through a nested JSON object and print key-value pairs.
🌐
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?

🌐
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

🌐
GeeksforGeeks
geeksforgeeks.org › python › loop-through-a-json-array-in-python
Loop through a JSON array in Python - GeeksforGeeks
July 23, 2025 - You can loop through a JSON array in Python by using the json module and then iterating through the array using a for loop. Let us see a few examples. In this example, we will define the JSON data as a string and load it using the and the load() ...
🌐
Tech-otaku
tech-otaku.com › mac › using-python-to-loop-through-json-encoded-data
Using Python to Loop Through JSON-Encoded Data – Tech Otaku
Apart from double-quotes " being replaced with single-quotes ', this output looks identical to the JSON-encoded data in our file. Remember however, what constitutes an array in the JSON-encoded data is now a Python list [] and what are objects in that same data are now Python dictionaries {}.
Find elsewhere
🌐
thisPointer
thispointer.com › home › iterators › how to iterate over a json object in python?
How to iterate over a JSON object in Python? - thisPointer
June 28, 2022 - Let’s see the ways to iterate over a JSON object. ... Iterate that dictionary (loaded) using for loop with an iterator. ... where the iterator is used to iterate the keys in a dictionary. Let’s see the example, to understand it better. In this example, we created a JSON string with 5 elements and iterate using for loop. # import JSON module import json # Consider the json string with 5 values input_json_string = '{ "tutorial-1": "python", \ "tutorial-2": "c++", \ "tutorial-3": "pandas", \ "tutorial-4": "numpy", \ "tutorial-5": ".net"}' # Load input_json_string into a dictionary-loaded loaded = json.loads(input_json_string) # Loop along dictionary keys for iterator in loaded: print(iterator, ":", loaded[iterator])
🌐
FreeKB
freekb.net › Article
Python (Scripting) - Loop through JSON list
January 10, 2024 - #!/usr/bin/python3 import json file = open('/path/to/example.json') try: parsed_json = json.load(file) except Exception as exception: print(f"Got the following exception: {exception}") file.close() for main in parsed_json['main']: for item in main['sub']: print(item['foo']) print(item['bar']) If so, consider buying me a coffee over at
🌐
Example Code
example-code.com › python › json_array_iterate.asp
CkPython Iterate over JSON Array containing JSON Objects
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • JavaScript • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
🌐
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
Answer (1 of 4): You have to do it recursively. Here is an example. [code]a_dict = {'a': 'a value', 'b': {'b.1': 'b.1 value'}} def iterate(dictionary): for key, value in dictionary.items(): if isinstance(value, dict): iterate(value) continue print('key {...
🌐
EyeHunts
tutorial.eyehunts.com › home › loop through json python
Loop through JSON Python
June 26, 2023 - import json # Sample JSON object json_data = ''' { "name": "John", "age": 30, "city": "New York", "pets": ["dog", "cat"] } ''' # Parse the JSON string into a Python object data = json.loads(json_data) # Loop through each key-value pair in the JSON object for key, value in data.items(): # Do something with the key-value pair print(key, ":", value)
🌐
EyeHunts
tutorial.eyehunts.com › home › python iterate over json array
Python iterate over JSON array
June 26, 2023 - Here’s the syntax for iterating over a JSON array in Python: import json # Example JSON array json_data = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35}]' # Parse JSON array into a Python object ...
🌐
Programster
blog.programster.org › python-iterate-over-massive-json-files
Python - Iterate Over Massive JSON Files | Programster's Blog
April 22, 2021 - <?php $numItems = 1000000; $items = []; for ($i=0; $i<$numItems; $i++) { $items[] = [ "uuid" => md5(rand()), "isActive" => md5(rand()), "balance" => md5(rand()), "picture" => md5(rand()), "age" => md5(rand()), "eyeColor" => md5(rand()), "name" => md5(rand()), "gender" => md5(rand()), "company" => md5(rand()), "email" => md5(rand()), "phone" => md5(rand()), "address" => md5(rand()), "about" => md5(rand()), "registered" => md5(rand()), "latitude" => md5(rand()), "longitude" => md5(rand()), ]; } file_put_contents(__DIR__ . '/data.json', json_encode($items, JSON_PRETTY_PRINT)); Ensure you have the ijson package installed by running: ... The script below demonstrates how we can loop over a massive JSON file without having to load it all into memory.
🌐
Restack
restack.io › p › nested-json-structure-examples-answer-iterate-through-nested-json-object-python
Iterate Through Nested Json Object Python | Restackio
Iterating through nested JSON structures in Python can be accomplished through various methods, including recursion, the itertools module, and list comprehensions. Each method has its advantages depending on the complexity of the JSON data and the specific requirements of your project.
🌐
TutorialsPoint
tutorialspoint.com › How-do-I-loop-through-a-JSON-file-with-multiple-keys-sub-keys-in-Python
How do I loop through a JSON file with multiple keys/sub-keys in Python?
March 5, 2020 - You can load it in your python program and loop over its keys in the following way − · import json f = open('data.json') data = json.load(f) f.close() ... Key: id Value: file Key: value Value: File Key: popup Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]} If you want to iterate over sub values as well, you'd have to write a recursive function that can iterate over this tree-like dict.
🌐
Python Forum
python-forum.io › thread-39669.html
Loop through json file and reset values [SOLVED]
March 23, 2023 - Hello everybody, I have a json file which stores information for different people, which looks like this: { "person": }Everytime my script get's executed I want to select a random person. Once the per
Top answer
1 of 2
22

data should be an ordinary collection at this point, so you'd iterate over it the same way you'd iterate over any other list/dict/whatever. The fact that it came from load doesn't incur any extra requirements on your part.

Here's an example that uses loads, which is similar in principle:

import json
my_json_data = "[1,2,3]"
data = json.loads(my_json_data)
for item in data:
    print(item)

Result:

1
2
3

Edit: if you're asking "how to I iterate over all the values in my data, including the ones contained inside deeply nested collections?", then you could do something like:

import json
my_json_data = """[
    1,
    {
        "2": 3,
        "4": [
            "5",
            "6",
            "7"
        ]
    },
    8,
    9
]"""

def recursive_iter(obj):
    if isinstance(obj, dict):
        for item in obj.values():
            yield from recursive_iter(item)
    elif any(isinstance(obj, t) for t in (list, tuple)):
        for item in obj:
            yield from recursive_iter(item)
    else:
        yield obj

data = json.loads(my_json_data)
for item in recursive_iter(data):
    print(item)

Result:

1
5
6
7
3
8
9

Edit: You can also keep track of the keys needed to navigate to each value, by passing them through the recursive calls and adding new keys to the collection as you pass over them.

def recursive_iter(obj, keys=()):
    if isinstance(obj, dict):
        for k, v in obj.items():
            yield from recursive_iter(v, keys + (k,))
    elif any(isinstance(obj, t) for t in (list, tuple)):
        for idx, item in enumerate(obj):
            yield from recursive_iter(item, keys + (idx,))
    else:
        yield keys, obj

data = json.loads(my_json_data)
for keys, item in recursive_iter(data):
    print(keys, item)

Result:

(0,) 1
(1, '2') 3
(1, '4', 0) 5
(1, '4', 1) 6
(1, '4', 2) 7
(2,) 8
(3,) 9
2 of 2
0

The previous solution is wrong, because if there is a leaf element that is [] or () or {}, it will not be printed (the 'for' loop to enumerate the object will not run). Here is a corrected solution:

def recursive_iter(obj, keys=()):
    if isinstance(obj, dict):
        if len(obj) == 0:
            yield keys, obj
        else:
            for k, v in obj.items():
                yield from recursive_iter(v, keys + (k,))
    elif any(isinstance(obj, t) for t in (list, tuple)):
        if len(obj) == 0:
            yield keys, obj
        else:
            for idx, item in enumerate(obj):
                yield from recursive_iter(item, keys + (idx,))
    else:
        yield keys, obj

a = {'a': (), 'b': [], 'c': 123, 'd': {}}

for i,j in recursive_iter(a):
    print(i,j)

This code prints:

('a',) ()
('b',) []
('c',) 123
('d',) {}