“str 索引必须是整数”是什么意思?意思是?

发布于 2024-08-31 03:27:07 字数 356 浏览 2 评论 0原文

我正在使用 jython 中的字典,这些字典是通过导入/解析 JSON 创建的。使用某些部分时,我会看到以下消息:

TypeError: str indices must be integers

当我执行以下操作时会发生这种情况:

if jsondata['foo']['bar'].lower() == 'baz':
    ...

Where jsondatalooks 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

上课铃就是安魂曲 2024-09-07 03:27:07

正如 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).

从﹋此江山别 2024-09-07 03:27:07

在从 dict 获取数据之前,您需要检查 dict 的类型以及 dict 中是否存在“z”。

>>> jsondata = {'a': '', 'b': {'z': True} }
>>> for key in jsondata:
...     if type(jsondata[key]) is dict and 'z' in jsondata[key].keys() and jsondata[key]['z'] is True:
...         print 'yes'
...
yes
>>>

或更短的 dict.get

>>> jsondata = {'a': '', 'b': {'z': True}, 'c' :{'zz':True}}
>>> for key in jsondata:
...     if type(jsondata[key]) is dict and jsondata[key].get('z',False):
...         print 'yes'
...
yes
>>>

You need to check the type for dict and existance of 'z' in the dict before getting data from dict.

>>> jsondata = {'a': '', 'b': {'z': True} }
>>> for key in jsondata:
...     if type(jsondata[key]) is dict and 'z' in jsondata[key].keys() and jsondata[key]['z'] is True:
...         print 'yes'
...
yes
>>>

or shorter one with dict.get

>>> jsondata = {'a': '', 'b': {'z': True}, 'c' :{'zz':True}}
>>> for key in jsondata:
...     if type(jsondata[key]) is dict and jsondata[key].get('z',False):
...         print 'yes'
...
yes
>>>
挽清梦 2024-09-07 03:27:07

实际上,您的语句应该引发 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文