从JSON字符串获取特定元素

2024-05-23 13:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个JSON字符串,它看起来像这样:

{"count": 100, 
 "facets": null, 
 "previous_page": null, 
 "results": [{"updated_at": "2013-09-17T13:45:13Z", "test_id": 194037042, "customer_id":       
              203793326, "id": 1954182}]

有更多的元素,但这只是我需要的一小部分。基本上,results有一个100个字典的列表,其中包含上面的元素“updated_at,test_id,customer_id,id”我需要做的是:

我需要一个id的所有值的列表。我不知道该怎么做,我试过做如下事情:

^{pr2}$

但我收到一条错误消息说:

print i['id']
TypeError: string indices must be integers

我做错什么了?在


Tags: 字符串testidjson元素列表countpage
2条回答

看起来您还没有使用将json加载到Python中json.loads(json_字符串)

即使你这样做了,你的“结果”也会是一个列表。在

试试这个:

import json

json_str = '{"count": 100, "facets": null, "previous_page": null, "results": [{"updated_at": "2013-09-17T13:45:13Z", "test_id": 194037042, "customer_id": 203793326, "id": 1954182}, {"updated_at": "2013-09-18T13:45:13Z", "test_id": 194037043, "customer_id": 203793327, "id": 1954183}]}'

data = json.loads(json_str)
result_ids = [result['id'] for result in data['results'] if 'id' in result]

输出:

^{pr2}$

然后,该代码将输出一个包含1954182和1954183的列表。 在这里使用列表理解以获得更快的速度和更少的代码行。它还确保结果dict在尝试访问它之前具有“id”属性。在

你没有做任何明显的错误。您的数据包含“null”元素,这些元素不是正确的python。这个很好用。在

my_dict = {"count": 100, 
 "facets": None, 
 "previous_page": None, 
 "results": [{"updated_at": "2013-09-17T13:45:13Z", "test_id": 194037042, "customer_id": 203793326, "id": 1954182}]
}

for i in my_dict['results']:
    print i['id']

您的错误意味着列表项之一是字符串,当您试图获取['id']元素时,错误正确地告诉您列表索引(字符串是字符列表)必须是整数。在

相关问题 更多 >