简体   繁体   中英

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM