从Json Python获取特定的字段值 [英] Getting specific field values from Json Python

查看:880
本文介绍了从Json Python获取特定的字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON文件,而我想做的就是获取此特定字段'_id'.问题是,当我使用json.load('input_file')时,它说我的变量data是一个列表,而不是字典,因此我无法执行以下操作:

I have a JSON file, and what I am trying to do is getting this specific field '_id'. Problem is that when I use json.load('input_file'), it says that my variable data is a list, not a dictionary, so I can't do something like:

for value in data['_id']:
    print(data['_id'][i])

因为我不断收到此错误: TypeError:列表索引必须是整数或切片,而不是str

because I keep getting this error: TypeError: list indices must be integers or slices, not str

我也想做的是:

data = json.load(input_file)[0]

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

It kinda works. Now, my type is a dictionary, and I can access like this: data['_id'] But I only get the first '_id' from the archive...

所以,我想做的是将所有'_id'的值添加到列表中,以备后用.

So, what I would like to do is add all '_id' 's values into a list, to use later.

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

感谢您的帮助!

[{
 "_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"
 }]

推荐答案

您要打印json列表中每个元素的_id,所以让我们通过简单地遍历元素来做到这一点:

You want to print the _id of each element of your json list, so let's do it by simply iterating over the elements:

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

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

If you want to transform the list of elements into a list of ids for later use, you can use list comprehension:

ids = [ e['_id'] for e in data ]  # get id from each element and create a list of them

这篇关于从Json Python获取特定的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆