Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues iterating through JSON list in Python?

I have a file with JSON data in it, like so:

{
    "Results": [
            {"Id": "001",
            "Name": "Bob",
            "Items": {
                "Cars": "1",
                "Books": "3",
                "Phones": "1"}
            },

            {"Id": "002",
            "Name": "Tom",
            "Items": {
                "Cars": "1",
                "Books": "3",
                "Phones": "1"}
            },

            {"Id": "003",
            "Name": "Sally",
            "Items": {
                "Cars": "1",
                "Books": "3",
                "Phones": "1"}
            }]
}

I can not figure out how to properly loop through the JSON. I would like to loop through the data and get a Name with the Cars for each member in the dataset. How can I accomplish this?

import json

with open('data.json') as data_file:
    data = json.load(data_file)

print data["Results"][0]["Name"] # Gives me a name for the first entry
print data["Results"][0]["Items"]["Cars"] # Gives me the number of cars for the first entry

I have tried looping through them with:

for i in data["Results"]:
print data["Results"][i]["Name"]    

But recieve an error: TypeError: list indices must be integers, not dict

like image 452
Bajan Avatar asked Jan 22 '16 16:01

Bajan


People also ask

How do you iterate through a JSON in Python?

Use json. loads() With the Help of the for Loop to Iterate Through a JSON Object in Python. A built-in package, json , is provided by Python, which can be imported to work with JSON form data. In Python, JSON exists as a string or stored in a JSON object.

How do I iterate through a list in JSON?

Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

How do you iterate through a list in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.


1 Answers

You are assuming that i is an index, but it is a dictionary, use:

for item in data["Results"]:
    print item["Name"]    

Quote from the for Statements:

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

like image 138
alecxe Avatar answered Oct 06 '22 05:10

alecxe