0

我有一个我进入 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}]

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

我需要获取所有值的列表,只是 id。我不知道该怎么做,我试过做这样的事情:

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

但我收到一条错误消息:

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

我究竟做错了什么?

4

2 回答 2

0

You are not doing anything obviously wrong. Your data includes 'null' elements which are not proper python. This works fine.

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']

The error you have implies that one of your list items is a string and when you are trying to get the ['id'] element the error rightly tells you that list indices (a string is a list of characters) must be integers.

于 2013-09-17T21:06:14.317 回答
0

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

即使你这样做了,你的“结果”字典实际上将是一个字典列表。

尝试这个:

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]

输出:

[1954182, 1954183]

然后,此代码将输出一个包含 1954182 和 1954183 的列表。在此处使用列表推导可以提高速度并减少代码行数。它还确保结果字典在尝试访问它之前具有“id”属性。

于 2013-09-17T21:20:21.107 回答