简体   繁体   English

Python 和 JSON 错误 - TypeError:字符串索引必须是整数

[英]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.我在解析 JSON 响应时收到错误 TypeError:字符串索引必须是整数。 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:从可测试的免费 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"] .该字典的(唯一)顶级键是 "RestResponse" 并且您的代码转换为: "RestResponse"["name"] Since it's a string, Python is expecting integer indices (like "RestResponse"[3] for slicing).由于它是一个字符串,因此 Python 需要整数索引(如用于切片的“RestResponse”[3])。

If you investigate the structure of the resulting dictionary you'll see that the results you want are under response.json()["RestResponse"]["result"] :如果您调查结果字典的结构,您将看到您想要的结果在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).代码中的 for 循环实际上是迭代dict (JSON 对象的解析版本)中的键。

When you iterable over response.json() you are just iterating over the str RestResponse which is the first element in your dict.当您迭代response.json()您只是在迭代 str RestResponse ,它是您的 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" => "result"

"RestResponse" : {
    "messages" : [...]
    "result" : [ {}, {}, {} ... ]
}

So to get the states you should get the values of the result array.因此,要获得状态,您应该获得result数组的值。

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.输出应该如预期的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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