![](/img/trans.png)
[英]python and json, Error - TypeError: string indices must be integers
[英]Python and JSON Error - TypeError: string indices must be integers
我在解析 JSON 響應時收到錯誤 TypeError:字符串索引必須是整數。 我不明白我做錯了什么,響應是一本字典..
從可測試的免費 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']))
迭代字典時,就是迭代它的鍵。 該字典的(唯一)頂級鍵是 "RestResponse" 並且您的代碼轉換為: "RestResponse"["name"]
。 由於它是一個字符串,因此 Python 需要整數索引(如用於切片的“RestResponse”[3])。
如果您調查結果字典的結構,您將看到您想要的結果在response.json()["RestResponse"]["result"]
:
for states in response.json()["RestResponse"]["result"]:
print ('{} {}'.format(states['name'], states['capital']))
出去:
Andhra Pradesh Hyderabad, India
Arunachal Pradesh Itanagar
Assam Dispur
Bihar Patna
Chhattisgarh Raipur
...
您的響應不是數組,而是對象。
代碼中的 for 循環實際上是迭代dict
(JSON 對象的解析版本)中的鍵。
當您迭代response.json()
您只是在迭代 str RestResponse
,它是您的 dict 中的第一個元素。
因此,您應該按如下方式更改代碼:
for states in response.json()['RestResponse']['result']:
print ('{} {}'.format(states['name'], states['capital']))
然后,您的輸出將是:
Andhra Pradesh Hyderabad, India
Arunachal Pradesh Itanagar
Assam Dispur
Bihar Patna
Chhattisgarh Raipur
Goa Panaji
Gujarat Gandhinagar
Haryana Chandigarh
Himachal Pradesh Shimla
...
您想要的結果在"RestResponse" => "result"
"RestResponse" : {
"messages" : [...]
"result" : [ {}, {}, {} ... ]
}
因此,要獲得狀態,您應該獲得result
數組的值。
request = requests.get('http://services.groupkt.com/state/get/IND/all')
response = request.json()
states = response["RestResponse"]["result"]
現在你可以這樣做:
for state in states:
print ('{} {}'.format(state['name'], state['capital']))
輸出應該如預期的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.