I'm using Python to parse through some JSON data for specific values. Specifically I want to pull the following:
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'
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?
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": []
},
This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function.
If you encounter this error message, double check to make sure you are using the numerical index value to access elements instead of a string value.
Each element in a list in Python has a unique position. This position is defined by an index.
The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)] .
Insted of fields['events']['public']
it should be fields['events'][0]['public']
print(fields['events'][0]['public'])
fields['events']
is a list so you need to use ['events'][0]
to access the dict inside the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With