从 Json Python 获取特定字段值

Mat*_*iel 2 python arrays json dictionary list

我有一个 JSON 文件,我想做的是获取这个特定字段“_id”。问题是当我使用json.load('input_file'),它说我的变量 data是一个列表,而不是字典,所以我不能做类似的事情:

for value in data['_id']:
    print(data['_id'][i])
Run Code Online (Sandbox Code Playgroud)

因为我不断收到此错误:TypeError: listindexsmust beintegers or slices, not str

我还尝试做的是:

data = json.load(input_file)[0]
Run Code Online (Sandbox Code Playgroud)

这有点管用。现在,我的类型是一本字典,我可以这样访问:data['_id'] 但我只从存档中获取第一个“_id”...

所以,我想做的是将所有 '_id' 的值添加到列表中,以供稍后使用。

input_file = open('input_file.txt')
data = json.load(input_file)[0] 
print(data['_id'])# only shows me the first '_id' value
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

[{
 "_id": "5436e3abbae478396759f0cf",
 "name": "ISIC_0000000",
 "updated": "2015-02-23T02:48:17.495000+00:00"
},
{
 "_id": "5436e3acbae478396759f0d1",
 "name": "ISIC_0000001",
 "updated": "2015-02-23T02:48:27.455000+00:00"
},
{

 "_id": "5436e3acbae478396759f0d3",
 "name": "ISIC_0000002",
 "updated": "2015-02-23T02:48:37.249000+00:00"
},
{
 "_id": "5436e3acbae478396759f0d5",
 "name": "ISIC_0000003",
 "updated": "2015-02-23T02:48:46.021000+00:00"
 }]
Run Code Online (Sandbox Code Playgroud)

zig*_*arn 5

您想要打印_idjson 列表中每个元素的 ,因此让我们通过简单地迭代元素来完成此操作:

input_file = open('input_file.txt')
data = json.load(input_file)  # get the data list
for element in data:  # iterate on each element of the list
    # element is a dict
    id = element['_id']  # get the id
    print(id)  # print it
Run Code Online (Sandbox Code Playgroud)

如果要将元素列表转换为 id 列表以供以后使用,可以使用列表理解:

ids = [ e['_id'] for e in data ]  # get id from each element and create a list of them
Run Code Online (Sandbox Code Playgroud)