Reputation: 1691
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']))
Upvotes: 3
Views: 3347
Reputation: 243
The results you want are under "RestResponse" => "result"
"RestResponse" : {
"messages" : [...]
"result" : [ {}, {}, {} ... ]
}
So to get the states you should get the values of the result
array.
request = requests.get('http://services.groupkt.com/state/get/IND/all')
response = request.json()
states = response["RestResponse"]["result"]
Now you can do:
for state in states:
print ('{} {}'.format(state['name'], state['capital']))
The Output should be as expected.
Upvotes: 0
Reputation:
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
...
Upvotes: 3
Reputation: 1067
When you iterable over response.json()
you are just iterating over the str RestResponse
which is the first element in your dict.
So, you should change your code as follows:
for states in response.json()['RestResponse']['result']:
print ('{} {}'.format(states['name'], states['capital']))
Then, your output will be:
Andhra Pradesh Hyderabad, India
Arunachal Pradesh Itanagar
Assam Dispur
Bihar Patna
Chhattisgarh Raipur
Goa Panaji
Gujarat Gandhinagar
Haryana Chandigarh
Himachal Pradesh Shimla
...
Upvotes: 0
Reputation: 2453
Your response is not an array, but an object.
The for loop in your code is actually iterating over the keys in a dict
(parsed version of the JSON object).
Upvotes: 0