[英]why am i getting this TypeError: string indices must be integers
我有這本詞典
response = {'body': '{"error": "Validation error'}','statusCode': 400}
我想得到元素“錯誤”
print(response["body"]["error"])
但這給了我
TypeError: string indices must be integers
我哪里錯了
你的問題是多余'
:
$ python test.py
File "C:\Users\pdunn\Downloads\test\test.py", line 1
response = {'body': '{"error": "Validation error'}','statusCode': 400}
^
SyntaxError: invalid syntax
刪除它們,它會工作:
response = {"body": {"error": "Validation error"}, "statusCode": 400}
print(response["body"]["error"])
$ python test.py
Validation error
另外,作為建議,與'
和"
保持一致。
可能response["body"]
是一個字符串(而不是您對待它的字典)。
嘗試使用以下方式打印其類型:
print(type(response["body"]))
如果它是str
,那么您可以使用json
模塊將其設為 dict:
import json
body = json.loads(response["error"])
print(body["error"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.