在 Python 中遍历 JSON 列表的问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34951448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:44:55  来源:igfitidea点击:

Issues iterating through JSON list in Python?

pythonarraysjsonfor-loop

提问by Bajan

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

我有一个包含 JSON 数据的文件,如下所示:

{
    "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?

我不知道如何正确循环 JSON。我想遍历数据并为数据集中的每个成员获取带有汽车的名称。我怎样才能做到这一点?

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

但是收到一个错误: TypeError:列表索引必须是整数,而不是字典

采纳答案by alecxe

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

您假设这i是一个索引,但它是一个字典,请使用:

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

Quote from the for Statements:

引自for 语句

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.

Python 中的 for 语句与您可能在 C 或 Pascal 中使用的语句略有不同。Python 的 for 语句不是总是迭代数字的等差数列(如在 Pascal 中),也不是让用户能够定义迭代步骤和停止条件(如 C),而是迭代任何序列(列表或一个字符串),按照它们在序列中出现的顺序

回答by geo_pythoncl

you are iterating through the dictionary not indexes so you should either use.

您正在遍历字典而不是索引,因此您应该使用。

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

or

或者

for i in range(len(data["Results"])):
    print data["Results"][i]["Name"]

回答by Tadhg McDonald-Jensen

The confusion is in how dictionaries and lists are used in iteration. A dictionary will iterate over it's keys (which you use as indices to get corresponding values)

混淆在于如何在迭代中使用字典和列表。字典将迭代它的键(您将其用作索引以获取相应的值)

x = {"a":3,  "b":4,  "c":5}
for key in x:   #same thing as using x.keys()
   print(key,x[key]) 

for value in x.values():
    print(value)      #this is better if the keys are irrelevant     

for key,value in x.items(): #this gives you both
    print(key,value)

but the default behaviour of iterating over a list will give you the elements instead of the indices:

但是迭代列表的默认行为会给你元素而不是索引:

y = [1,2,3,4]
for i in range(len(y)):  #iterate over the indices
    print(i,y[i])

for item in y:
    print(item)  #doesn't keep track of indices

for i,item in enumerate(y): #this gives you both
    print(i,item)

If you want to generalize your program to handle both types the same way you could use one of these functions:

如果您想将您的程序概括为以相同的方式处理这两种类型,您可以使用以下函数之一:

def indices(obj):
    if isinstance(obj,dict):
        return obj.keys()
    elif isinstance(obj,list):
        return range(len(obj))
    else:
        raise TypeError("expected dict or list, got %r"%type(obj))

def values(obj):
    if isinstance(obj,dict):
        return obj.values()
    elif isinstance(obj,list):
        return obj
    else:
        raise TypeError("expected dict or list, got %r"%type(obj))

def enum(obj):
    if isinstance(obj,dict):
        return obj.items()
    elif isinstance(obj,list):
        return enumerate(obj)
    else:
        raise TypeError("expected dict or list, got %r"%type(obj))

this way if you, for example, later changed the json to store the results in a dict using the id as keys the program would still iterate through it the same way:

这样,例如,如果您稍后更改 json 以使用 id 作为键将结果存储在 dict 中,程序仍会以相同的方式遍历它:

#data = <LOAD JSON>
for item in values(data["Results"]):
    print(item["name"])

#or
for i in indices(data["Results"]):
    print(data["Results"][i]["name"])

回答by mukesh mali

for json_data in data['Results']:
    for attribute, value in json_data.iteritems():
        print attribute, value # example usage