简体   繁体   English

为什么我会收到这个 TypeError:字符串索引必须是整数

[英]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.

相关问题 为什么会出现TypeError:字符串索引必须为整数? - Why am I getting TypeError: string indices must be integers? 为什么我看到“TypeError:字符串索引必须是整数”? - Why am I seeing "TypeError: string indices must be integers"? 为什么我的函数会出现“TypeError:字符串索引必须是整数”? - Why am I getting "TypeError: string indices must be integers" on my function? 我收到python错误TypeError:字符串索引必须是整数,而不是str - I am getting python error TypeError: String indices must be integers, not str 我为什么会收到此错误TypeError:列表索引必须是整数或切片,而不是str - Why am I getting this error TypeError: list indices must be integers or slices, not str 为什么我在索引字典时会收到“字符串索引必须是整数”错误? - Why am I getting a “String indices must be integers” error when I am indicing a dictionary? 获取类型错误:字符串索引必须是整数。 不知道为什么 - Getting TypeError: string indices must be integers. Not Sure Why 我收到一个typeError:字符串索引必须是整数,而不是type - I'm getting a typeError: string indices must be integers, not type 我收到此错误-> TypeError:字符串索引必须为整数 - I'm getting this error --> TypeError: string indices must be integers TypeError:字符串索引必须是整数,为什么? - TypeError: string indices must be integers, why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM