使用 Python 解析 JSON:TypeError:列表索引必须是整数,而不是 str

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25855276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:44:57  来源:igfitidea点击:

Parsing JSON with Python: TypeError: list indices must be integers, not str

pythonjson

提问by FunnyChef

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

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

  • author_id
  • created_at
  • public
  • 作者_id
  • created_at
  • 民众

The Python code looks like;

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'

My code errors with:

我的代码错误:

File "get_ticket_updates.py", line 27, in <module>
print(fields['events']['public'])
TypeError: list indices must be integers, not str

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

我知道 public 的值是一个字符串,它需要是整数,所以我该如何处理?

The data looks like:

数据看起来像:

{

"audits": [
    {

        "id": 20994687984,
        "ticket_id": ####,
        "created_at": "2014-09-15T16:30:11Z",
        "author_id": 312016568,
        "via": {
            "channel": "email",
            "source": {
                "from": {
                    "address": "[email protected]",
                    "name": "user name",
                    "original_recipients": [
                        "[email protected]",
                        "[email protected]"
                    ]
                },
                "to": {
                    "address": "[email protected]",
                    "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": []
            },

采纳答案by Vizjerei

Insted of fields['events']['public']it should be fields['events'][0]['public']

的insted的fields['events']['public']应该是fields['events'][0]['public']

回答by Padraic Cunningham

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

fields['events']is a list so you need to use ['events'][0]to access the dict inside the list.

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

回答by Daniel Roseman

It's exactly as the error says. fields['events']is a list, so you can't index it with ['public']. You need to iterate through the values, each of which is a dictionary.

这正是错误所说的。fields['events']是一个列表,所以你不能用['public']. 您需要遍历值,每个值都是一个字典。

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