简体   繁体   English

从JSON字符串获取特定元素

[英]Getting a specific element from a JSON string

I have a JSON string that i got into python that looks something like this: 我有一个进入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}]

There are more elements but this is a small cut of what i need. 还有更多元素,但这只是我需要的一小部分。 Basically, results has a list of 100 dictionaries that contain the elements above "updated_at, test_id, customer_id, id" What i need to do is the following: 基本上,结果有一个包含100个词典的列表,这些词典包含上面的元素“ updated_at,test_id,customer_id,id”,我需要做的是:

I need to get a list of all of the values of JUST the id. 我需要获取ID的所有值的列表。 I am not sure how to go about this though, i have tried doing things like: 我不确定如何去做,我尝试做类似的事情:

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

but i get an error message that says: 但我收到一条错误消息,内容为:

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

What am i doing wrong? 我究竟做错了什么?

You are not doing anything obviously wrong. 您没有做任何明显错误的事情。 Your data includes 'null' elements which are not proper python. 您的数据包含不正确的python的'null'元素。 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. 您所犯的错误意味着您的列表项之一是字符串,并且当您尝试获取['id']元素时,该错误正确地告诉您列表索引(字符串是字符列表)必须是整数。

It looks like you haven't loaded the json into Python with json.loads(json_string) 看起来您尚未使用json.loads(json_string)将json加载到Python中

And even after you do that, your "results" dict is actually going to be a list of dicts. 即使执行了此操作,您的“结果”字典实际上也将成为字典列表。

Try this: 尝试这个:

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]

Output: 输出:

[1954182, 1954183]

This code would then output a list containing 1954182 and 1954183. Use a list comprehension here for greater speed and less lines of code. 然后,此代码将输出包含1954182和1954183的列表。在此处使用列表理解可以提高速度,减少代码行数。 It also ensures that the result dict has an 'id' attribute before trying to access it. 它还可以确保结果字典在尝试访问它之前具有“ id”属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM