[英]why am i getting this TypeError: string indices must be integers
I have this dictionary我有这本词典
response = {'body': '{"error": "Validation error'}','statusCode': 400}
i want to get the element "error"我想得到元素“错误”
print(response["body"]["error"])
but this gives me但这给了我
TypeError: string indices must be integers
where am i going wrong我哪里错了
You issue is with the superfluous '
s:你的问题是多余'
:
$ python test.py
File "C:\Users\pdunn\Downloads\test\test.py", line 1
response = {'body': '{"error": "Validation error'}','statusCode': 400}
^
SyntaxError: invalid syntax
Remove them and it'll work:删除它们,它会工作:
response = {"body": {"error": "Validation error"}, "statusCode": 400}
print(response["body"]["error"])
$ python test.py
Validation error
Also, as advice, be consistent with '
and "
.另外,作为建议,与'
和"
保持一致。
Probably response["body"]
is a string (not a dictionary as you are treating it as).可能response["body"]
是一个字符串(而不是您对待它的字典)。
Try printing its type with:尝试使用以下方式打印其类型:
print(type(response["body"]))
If it is str
, then you can make it a dict with the json
module:如果它是str
,那么您可以使用json
模块将其设为 dict:
import json
body = json.loads(response["error"])
print(body["error"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.