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

python json dict iterate {key: value} are the same - Stack Overflow
I have tried using .items() and ... over the keys via iterkeys() and keys() to no avail. I can call it direct via json_dict['Destination_IP'] and the value returns. for json_dict in data: if 'Destination_IP' in json_dict.keys(): print json_dict['Destination_IP'] ... I'm on python 2.7, so any ... More on stackoverflow.com
🌐 stackoverflow.com
Advice on how to iterate through JSON to find the first instance of a key value pair?
Is the index sorted in the json? If yes, you can just iterate over the codecs in the json and pick the first one that is audio. for stream in jsondata['streams']: if stream['codec_type']=="audio": cname = stream['codec_name'] break print(cname) More on reddit.com
🌐 r/learnpython
5
1
September 5, 2023
How to iterate through JSON object in Python and get KEY? - Stack Overflow
You can iterate over the keys of your jsonObject where the values of each item is a list. Then iterate through each list of dictionaries and get the key-value pair. More on stackoverflow.com
🌐 stackoverflow.com
November 28, 2019
Iterate through a json list and get specific key and value with Python - Stack Overflow
I have a JSON list like this (it was a JSON response, the below is after i did json.loads) [{'status': 'ok', 'slot': None, 'name': 'blah', 'index': 0, 'identify': 'off', 'details': None, 'speed':... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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 json.loads() method is used to parse a JSON-formatted string into a Python dictionary. Once the JSON data is in dictionary form, we can employ a for loop to iterate through its keys and access the corresponding values.
🌐
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])
🌐
Reddit
reddit.com › r/learnpython › advice on how to iterate through json to find the first instance of a key value pair?
r/learnpython on Reddit: Advice on how to iterate through JSON to find the first instance of a key value pair?
September 5, 2023 -

I have an undesirable JSON object that I can't modify:

{
"programs": [

],
"streams": [
    {
        "index": 0,
        "codec_name": "hevc",
        "codec_type": "video"
    },
    {
        "index": 1,
        "codec_name": "aac",
        "codec_type": "audio"
    },
    {
        "index": 2,
        "codec_name": "opus",
        "codec_type": "audio"
    },
    {
        "index": 3,
        "codec_name": "ac3",
        "codec_type": "audio"
    },
    {
        "index": 4,
        "codec_name": "ass",
        "codec_type": "subtitle"
    },
    {
        "index": 5,
        "codec_name": "ttf",
        "codec_type": "attachment"
       }
       ]
}

This is psudo json from the very real output of ffprobe -loglevel error -show_entries format:stream=index,stream,codec_type,codec_name -of json FILENAME

I need to get the first codec_name from the lowest index of the codec_type: audio.

In this case, index 1, 2, and 3 are all of codec_type: audio, so the lowest index/first instance would be 1 and my codec_name would be aac.

Any ideas on how to move forward on a problem like this? I can't seem to find any stackoverflow threads with anything similar.

----------------------------

EDIT, solution here: https://www.reddit.com/r/learnpython/comments/16af8zf/comment/jz74hc9/?utm_source=share&utm_medium=web2x&context=3

Thank you u/shiftybyte, u/djshadesuk!!!

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 59074990 › how-to-iterate-through-json-object-in-python-and-get-key
How to iterate through JSON object in Python and get KEY? - Stack Overflow
November 28, 2019 - # get keys of jsonObject for item in jsonObject: # loop through each list for list_item in jsonObject[item]: # for each list get the key,value pair for keys in list_item: print (f"(Key,Value)=>({keys}, {list_item[keys]})") ... Sign up to request ...
🌐
CodeSpeedy
codespeedy.com › home › how to loop through json with subkeys in python
How to loop through JSON with subkeys in Python - CodeSpeedy
January 20, 2020 - Now to iterate with keys, see the below code. import json with open('json_multidimensional.json','r') as string: my_dict=json.load(string) string.close() for k in my_dict: print("key:"+k+", value:"+str(my_dict[k])) ... key:website, value:codespeedy ...
🌐
EyeHunts
tutorial.eyehunts.com › home › loop through json python
Loop through JSON Python
June 26, 2023 - import json # JSON data json_data = '{"name": "John", "age": 30, "city": "New York"}' # Parse the JSON string into a Python object data = json.loads(json_data) # Loop through each key in the JSON object for key in data: # Access the value using the key value = data[key] # Do something with the key-value pair print(key, ":", value)
🌐
TutorialsPoint
tutorialspoint.com › How-do-I-loop-through-a-JSON-file-with-multiple-keys-sub-keys-in-Python
How can I loop over entries in JSON using Python?
March 5, 2020 - For example, if you have a json with the following content − · { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } You can load it in your python program and loop over its keys in the following way − ·
🌐
YouTube
youtube.com › codegen
python iterate over json key value - YouTube
Download this code from https://codegive.com Title: Iterating Over JSON Key-Value Pairs in Python: A Comprehensive TutorialIntroduction:JSON (JavaScript Obje...
Published: January 19, 2024
Views: 3
🌐
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.
🌐
Reddit
reddit.com › r/learnpython › using python to loop through json dictionary that re-uses the same key?
r/learnpython on Reddit: Using Python to loop through JSON dictionary that re-uses the same key?
October 13, 2022 -

I'm trying to restructure JSON output from a API to the specific format that Ansible wants for it's invetory file. To do this I thought I would loop through the JSON and grab the variables I need and then feed that into the proper structure. However, I noticed my API JSON is using the same $ key for multiple variables. How can I properly reference and differentiate between the variables? Here is an example:

 "model-responses": {
        "model": [
            {
                "@mh": "0x11e013",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch1"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "Raritan Computer, Inc.DV"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.1"
                    },
                    {
                        "@id": "0x10052",
                        "$": "PX2 030610"
                    }
                ]
            },
            {
                "@mh": "0x115014",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch2"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "DCS-7010T-48"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.2"
                    },
                    {
                        "@id": "0x10052",
                        "$": "Arista Networks EOS version 4.22.3M-INT running on an Arista Networks DCS-7010T-48"
                    }
                ]
            },
🌐
Stack Overflow
stackoverflow.com › questions › 38022136 › iterate-through-every-key-value-in-json-dictionary-in-python
Iterate through every key value in JSON dictionary in Python - Stack Overflow
May 24, 2017 - I converted the above mentioned string to a dictionary in somerandomFunc() and then sent this dictionary to iterator(). Iterator() will recursively check if the value in each key-value pair is a dictionary or not. If the value is not a dictionary, it will send the key to smartScanner() where I will be replacing the value of the recieved key with myTestString · def somerandomfunc(self,JSONString): payload=simplejson.loads(JSONString) self.payload=payload iterator(payload) def iterator(self,payload): for i in payload: if isinstance(payload[i],dict): self.iterator(payload[i]) else: self.smartScanner(i) def smartScanner(self,i): mytestString='">qqqq' if (self.payload.has_key(i)): self.payload[i]=mytestString print "%s:%s"%(i,self.payload.has_key(i))
🌐
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 - While I was working on a Python ... is actually a dict inside Python), search for a specific field (key) and if the value of this key meets a condition, print the parent (top layer) key....
Top answer
1 of 2
1

Let me de-construct your code assuming json is a dictionary with the data {u'key2': u'xyz', u'key1': u'abc'}

test = [{'a': j['key1'], 'token':j['key2']} for j in json ]

What you were actually doing is iterating through the key in the dictionary and then treating the result as a dictionary, this will give you an error!

The j in json in each loop is the key, so in the first iteration you get the result 'key1' and when you try j['key1'] you assumed that j is a dictionary, but in fact it is a string, hence the error TypeError: string indices must be integers.

This is probably what you are looking for to help you with your solution.

This will give you a list of dictionaries:

test = [{key, value} for key, value in json.items()]

The result:

[{u'key2': u'xyz'}, {u'key1': u'abc'}]

The reason your code failed is because you were trying to unnecessarily iterate through the dictionary, but if you wish to disassemble it simply do this:

[dict(a=json['key1'], token=json['key2'])]

Result:

[{'a': u'abc', 'token': u'xyz'}]
2 of 2
1

I was just looking for a way to make the code a little more fault tolerant and able to handle both single and multiple objects

The easy way to do that is to check the type of data coming in and change it into a standardized form that the rest of your code can consume. If you get a dict just create a list to hold the dict and the rest of the code will work.

json = request.get_json(force=True) # receives request from postman
for j in json:
        print str(j)

if isinstance(json, dict):
    json = [json]
test = [{'a': j['key1'], 'token':j['key2']} for j in json ]
🌐
Stack Overflow
stackoverflow.com › questions › 54611188 › iterate-over-json-and-parse-key-value-pair
python - Iterate over json and parse key value pair - Stack Overflow
json_data = json.loads(response.text) print json_data for key, value in json_data.items(): print key, value · I want to translate it into a list like [James, 51202], [Jim, 32304] so that I can easily use. Or, I'd like to just get key value pairs so that I can iterate over them. python ·
Top answer
1 of 2
3

Test key existence in attributes to retrieve the different values:

df = []

for item in json_response["items"]:
    errors = "NA" 
    if "errors" in item["attributes"]
        errors = item["attributes"]["errors"]
    elif "RefreshFailure" in item["attributes"]:
        errors = item["attributes"]["RefreshFailure"] 

    df.append({
        'AccountName': item["accountName"],
        'Action': item["action"],
        'Application': item["application"],
        'AppID': item["attributes"]["appId"],
        'AppName': item["attributes"]["AppName"],
        'Errors': errors,
        'ContextID': item["contextid"],
        'Created': item["created"],
        'HostName': item["hostname"],
        'EventID': item["id"],
        'Info': item["info"],
        'ipaddr': item["ipaddr"],
        'EventSource': item["source"],
        'Stack': item["stack"],
        'Target': item["target"],
        'TrackingID': item["trackingId"],
        'Type': item["type"]
    })
2 of 2
0

I tried to emulate your data to make the code work.

import json
from pprint import pprint


json_data = '''
{
    "items": [
        {
            "accountName": null,
            "action": "Disable",
            "application": "Application1",
            "attributes": {
                "appId": "7d264050024",
                "AppName": "Application1",
                "errors": [
                    "Rule: Rule not found."
                ]
            },
            "contextid": null,
            "created": 1553194821098,
            "hostname": null,
            "id": "ac09ea0082",
            "info": null,
            "ipaddr": null,
            "source": "System1",
            "stack": null,
            "target": "TargetName1.",
            "trackingId": null,
            "type": null
        },
        {
            "accountName": null,
            "action": "Disable",
            "application": "Application1",
            "attributes": {
                "appId": "7d2451684288",
                "cloudAppName": "Application1",
                "RefreshFailure": true
            },
            "contextid": null,
            "created": 1553194821098,
            "hostname": null,
            "id": "ac09ea0082",
            "info": null,
            "ipaddr": null,
            "source": "System1",
            "stack": null,
            "target": "TargetName1.",
            "trackingId": null,
            "type": null
        }
    ]
}'''
json_response = json.loads(json_data)


def capitalize(s):
    return s[0].upper() + s[1:]


df = []

for item in json_response["items"]:
    d = {}
    # Iterate over the items in the dictionary/json object and add them one by one using a loop
    # This will work even if the items in the json_response changes without having to change the code
    for key, value in item.items():
        # "attributes" is itself a dictionary/json object
        # Its items have to be unpacked and added instead of adding it as a raw object
        if isinstance(value, dict):
            for k, v in value.items():
                d[capitalize(k)] = v
        else:
            d[capitalize(key)] = value

    df.append(d)

pprint(df)

Output:

[{'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d264050024',
  'AppName': 'Application1',
  'Application': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Errors': ['Rule: Rule not found.'],
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None},
 {'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d2451684288',
  'Application': 'Application1',
  'CloudAppName': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'RefreshFailure': True,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None}]

If you want the key name to be Errors even when the actual key name is RefreshFailure, you can add these lines of code before df.append(d)

...
if 'RefreshFailure' in d:
    d['Errors'] = d['RefreshFailure']
    del d['RefreshFailure']

df.append(d)

With these few extra lines of code, the output would look like this:

[{'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d264050024',
  'AppName': 'Application1',
  'Application': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Errors': ['Rule: Rule not found.'],
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None},
 {'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d2451684288',
  'Application': 'Application1',
  'CloudAppName': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Errors': True,
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None}]