-2

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)
AMC
  • 2,642
  • 7
  • 13
  • 35
  • 3
    You mean `sig_count = parsed["attributes"]["signature_count"]` – blhsing Mar 12 '20 at 21:32
  • Please provide the entire error message. If you're using requests, don't waste time with the `json.loads()` and just call `response.json()`. – AMC Mar 13 '20 at 00:50
  • Does this answer your question? [Why am I seeing "TypeError: string indices must be integers"?](https://stackoverflow.com/questions/6077675/why-am-i-seeing-typeerror-string-indices-must-be-integers) – AMC Mar 13 '20 at 00:51

2 Answers2

2

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']

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
2

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.

Peter
  • 169
  • 5