JSON TypeError: string indices must be integers

729 views Asked by At

I get the error "TypeError: string indices must be integers" in the following code.

import json

import requests

url = "https://petition.parliament.uk/petitions/300139.json"

response = requests.get(url)
data = response.text
parsed = json.loads(data)

sig_count = data["attributes"]["signature_count"]

print(sig_count)
2

There are 2 answers

0
Peter On BEST ANSWER

import json

url = 'https://petition.parliament.uk/petitions/300139.json'

response = requests.get(url)
data = response.text

parsed = json.loads(data)

sig_count = parsed["data"]["attributes"]["signature_count"]

print(sig_count)    

you are calling the variable data instead of parsed. You are also missing the "data" key when filtering.

0
Celius Stingher On

After using json.loads(), you need to use the newly defined variable because the opreration does not happen in place. data` is the json in its raw form, interpreted as a string.

Try with:

parsed['attributes']['signature_count']