Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and JSON Error - TypeError: string indices must be integers

Tags:

python

json

rest

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']))
like image 771
Terry Avatar asked May 28 '26 21:05

Terry


1 Answers

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
...