Home > Mobile >  Iterating though nested JSON values with python
Iterating though nested JSON values with python

Time:06-27

I want to be able to iterate through nested values in a JSON file and add them to a list.

For example, I want to find the values contained in each instance of Test below.

 A= {"Tags": [
                {
                    "Item":{
                        "Test":"mouse",
                    },
                },
                {
                    "Item":{
                        "Test":"dog",
                    },
                },
                {
                    "Item":{
                        "Test":"cat",
                    },
                },
                {
                    "Item":{
                        "Test":"dog",
                    },
                }
            ]
        }

I can select values individually like so:

print(A['Tags'][1]['Item']['Test'])

But I can't iterate over the entire JSON file.

CodePudding user response:

I have a simpler method: use the jsonpath package

You can learn jsonpath, which is very convenient, but the disadvantage is that it is slow

from jsonpath import jsonpath

A = {"Tags": [
    {
        "Item": {
            "Test": "mouse",
        },
    },
    {
        "Item": {
            "Test": "dog",
        },
    },
    {
        "Item": {
            "Test": "cat",
        },
    },
    {
        "Item": {
            "Test": "dog",
        },
    }
]
}

print(jsonpath(A, "$..Test"))

out

['mouse', 'dog', 'cat', 'dog']

CodePudding user response:

for tag in A['Tags']:
    print(tag['Item']['Test'])

A['Tags'] is just a list of objects/dictionary, which is referred by tag and then you can access any value inside the object via a key.

CodePudding user response:

This iterates over the whole and appends each value to a list.

output = list()

for tag in A['Tags']:
    output.append(tag['Item']['Test'])

If you're worried about missing values, the following will correct for that.

output = list()

for tag in A['Tags']:
    if item := tag.get('Item', dict()).get('Test'):
        output.append(item)

Output:

['mouse', 'dog', 'cat', 'dog']
  • Related