使用Python解析JSON:TypeError:列表索引必须是整数而不是字符串。

10
我将使用Python来解析一些JSON数据,以获取特定的值。具体来说,我想提取以下内容:
  • author_id
  • created_at
  • public
Python代码如下:
import json
import requests

# Set the request parameters
url = 'https:<MYURL.json'
user = 'MY_USER'
pwd = 'MY_PWD'

# Do the HTTP get request
response = requests.get(url, auth=(user, pwd))

# Check for HTTP codes other than 200
if response.status_code != 200: 
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()

# Decode the JSON response
data = response.json()

# Print each value

field_list = data['audits']
for fields in field_list:
print(fields['author_id'])
print(fields['created_at'])
print(fields['events']['public'])
print '\n'

我的代码出现了错误:
File "get_ticket_updates.py", line 27, in <module>
print(fields['events']['public'])
TypeError: list indices must be integers, not str

我知道public的值是一个字符串,需要转换成整数,那么我该怎么处理呢?

数据看起来像这样:

{

"audits": [
    {

        "id": 20994687984,
        "ticket_id": ####,
        "created_at": "2014-09-15T16:30:11Z",
        "author_id": 312016568,
        "via": {
            "channel": "email",
            "source": {
                "from": {
                    "address": "email@domain.com",
                    "name": "user name",
                    "original_recipients": [
                        "email@domain.com",
                        "email@domain.com"
                    ]
                },
                "to": {
                    "address": "email@domain.com",
                    "name": "My Portal"
                },
                "rel": null
            }
        },
    },
 {
        "id": 20994845144,
        "ticket_id": ####,
        "created_at": "2014-09-15T16:32:18Z",
        "author_id": 233915468,
        "via": {
            "channel": "web",
            "source": {
                "from": {},
                "to": {},
                "rel": null
            }
        },
        "events": [
            {
                "id": 20994845154,
                "type": "Comment",
                "author_id": 233915468,
                "body": "<SOME TEXT>",
                "public": true,
                "attachments": []
            },

听取错误信息。找到导致错误的原因(例如表达式)。调和所信任的值/状态/行为和实际的值/状态/行为。 - user2864740
最小可重现代码:l = []; l['foo'];错误与解析 JSON 无关,而是由于使用结果 Python 对象图的方式不正确引起的。 - user2864740
3个回答

39

应该使用fields['events'][0]['public'],而不是fields['events']['public']


3
如果我可以多次顶起这个答案,我一定会这样做。感谢您让我恢复理智。 - Dan

5
print(fields['events'][0]['public'])

fields['events'] 是一个列表,因此您需要使用 ['events'][0] 来访问列表中的字典。


3

正如错误所述,fields['events']是一个列表,因此您无法使用['public']进行索引。您需要遍历其中的值,每个值都是一个字典。

for event in fields['events']:
    print event['public']

只有一个字典在里面。 - Padraic Cunningham
在那个样本数据中,是的。但显然并不总是这样,否则它一开始就不会是一个列表。 - Daniel Roseman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接