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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With