“str 索引必须是整数”是什么意思?意思是?
我正在使用 jython 中的字典,这些字典是通过导入/解析 JSON 创建的。使用某些部分时,我会看到以下消息:
TypeError: str indices must be integers
当我执行以下操作时会发生这种情况:
if jsondata['foo']['bar'].lower() == 'baz':
...
Where jsondata
looks like:
{'foo': {'bar':'baz'} }
这是什么意思,以及如何修复它?
I'm working with dicts in jython which are created from importing/parsing JSON. Working with certain sections I see the following message:
TypeError: str indices must be integers
This occurs when I do something like:
if jsondata['foo']['bar'].lower() == 'baz':
...
Where jsondata
looks like:
{'foo': {'bar':'baz'} }
What does this mean, and how do I fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Marcelo 和 Ivo 所说,听起来您正在尝试访问原始 JSON 字符串,而不首先通过 json.loads(my_json_string) 将其解析为 Python。
As Marcelo and Ivo say, it sounds like you're trying to access the raw JSON string, without first parsing it into Python via
json.loads(my_json_string)
.在从 dict 获取数据之前,您需要检查 dict 的类型以及 dict 中是否存在“z”。
或更短的 dict.get
You need to check the type for dict and existance of 'z' in the dict before getting data from dict.
or shorter one with dict.get
实际上,您的语句应该引发
SyntaxError: can't allocate to function call
因为您缺少=
并因此进行赋值而不是检查相等性。由于我在运行您显示的代码时没有收到 TypeError,因此我想您首先修复丢失的
=
,然后再检查 Stacktrace 的内容。但也有可能您的 jsondata 尚未解码,因此仍然是纯文本,这当然会引发索引错误。
Actually your statement should raise
SyntaxError: can't assign to function call
due to the fact that you're missing a=
and thus making an assignment instead of a check for equality.Since I don't get the TypeError when running the code you've shown, I suppose that you first fix the missing
=
and after that check back on what the Stacktrace says.But it might also be possible that your jsondata hasn't been decoded and therefore is still plain text, which would of course then raise the indexing error.