I'm receiving the error TypeError: string indices must be integers when parsing a JSON response. I don't see what I'm doing wrong, the response is a dictionary..
A sample of my code that gets the same error from a testable free REST API:
import requests
response = requests.get('http://services.groupkt.com/state/get/IND/all')
for states in response.json():
print ('{} {}'.format(states['name'], states['capital']))
When you iterate over a dictionary, you iterate over its keys. The (only) top-level key for that dictionary is "RestResponse" and your code translates to: "RestResponse"["name"]. Since it's a string, Python is expecting integer indices (like "RestResponse"[3] for slicing).
If you investigate the structure of the resulting dictionary you'll see that the results you want are under response.json()["RestResponse"]["result"]:
for states in response.json()["RestResponse"]["result"]:
print ('{} {}'.format(states['name'], states['capital']))
Out:
Andhra Pradesh Hyderabad, India
Arunachal Pradesh Itanagar
Assam Dispur
Bihar Patna
Chhattisgarh Raipur
...
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