使用Python解析JSON:TypeError:列表索引必须是整数,而不是str [英] Parsing JSON with Python: TypeError: list indices must be integers, not str

查看:211
本文介绍了使用Python解析JSON:TypeError:列表索引必须是整数,而不是str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python解析一些JSON数据以获取特定值.具体来说,我想提出以下几点:

I'm using Python to parse through some JSON data for specific values. Specifically I want to pull the following:

  • author_id
  • created_at
  • 公开

Python代码如下;

The Python code looks like;

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的值是一个字符串,它必须是整数,因此,我该如何处理呢?

I get that the value of public is a string and it needs to to be integer so, how can I work with this?

数据如下:

{

"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": []
            },

推荐答案

fields['events']['public']插入,应该为fields['events'][0]['public']

这篇关于使用Python解析JSON:TypeError:列表索引必须是整数,而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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