我是靠谱客的博主 干净世界,最近开发中收集的这篇文章主要介绍python json解析 建索引_使用Python解析JSON:TypeError:列表索引必须是整数,而不是str...,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

author_id

created_at

public

The Python code looks like;

import json

import requests

# Set the request parameters

url = 'https:

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

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?

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@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": "",

"public": true,

"attachments": []

},

解决方案

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

最后

以上就是干净世界为你收集整理的python json解析 建索引_使用Python解析JSON:TypeError:列表索引必须是整数,而不是str...的全部内容,希望文章能够帮你解决python json解析 建索引_使用Python解析JSON:TypeError:列表索引必须是整数,而不是str...所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部