小编Mat*_*iel的帖子

从 Json Python 获取特定字段值

我有一个 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)

python arrays json dictionary list

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

arrays ×1

dictionary ×1

json ×1

list ×1

python ×1