gpt4 book ai didi

python - 类型错误 : string indices must be integers while parsing JSON using Python?

转载 作者:IT老高 更新时间:2023-10-28 20:50:08 27 4
gpt4 key购买 nike

我现在很困惑为什么我不能解析这个 JSON 字符串。类似的代码适用于其他 JSON 字符串,但不适用于这个 - 我正在尝试解析 JSON 字符串并从 JSON 中提取脚本。

下面是我的代码。

for step in steps:
step_path = '/example/v1' +'/'+step

data, stat = zk.get(step_path)
jsonStr = data.decode("utf-8")
print(jsonStr)
j = json.loads(json.dumps(jsonStr))
print(j)
shell_script = j['script']
print(shell_script)

所以第一个 print(jsonStr) 会打印出这样的东西 -

{"script":"#!/bin/bash\necho Hello world1\n"}

而第二个 print(j) 会打印出类似这样的内容 -

{"script":"#!/bin/bash\necho Hello world1\n"}

然后第三个打印没有被打印出来,它给出了这个错误 -

Traceback (most recent call last):
File "test5.py", line 33, in <module>
shell_script = j['script']
TypeError: string indices must be integers

所以我想知道我在这里做错了什么?

我已经使用上面相同的代码来解析 JSON,它工作正常..

最佳答案

问题在于 jsonStr 是一个字符串,它用 JSON 编码某些对象,而不是实际的对象。

你显然知道它是一个字符串,因为你称它为jsonStr。这条线有效的事实证明了这一点:

jsonStr = data.decode("utf-8")

所以,jsonStr 是一个字符串。对字符串调用 json.dumps 是完全合法的。该字符串是某个对象的 JSON 编码还是您的姓氏都没有关系;您可以在 JSON 中对该字符串进行编码。然后你可以解码那个字符串,取回原来的字符串。

所以,这个:

j = json.loads(json.dumps(jsonStr))

... 将返回与 j 中的 jsonStr 完全相同的字符串。您还没有解码到原始对象。

为此,不要进行额外的编码:

j = json.loads(jsonStr)

如果不清楚,请尝试使用交互式终端:

>>> obj = ['abc', {'a': 1, 'b': 2}]
>>> type(obj)
list
>>> obj[1]['b']
2
>>> j = json.dumps(obj)
>>> type(j)
str
>>> j[1]['b']
TypeError: string indices must be integers
>>> jj = json.dumps(j)
>>> type(jj)
str
>>> j
'["abc", {"a": 1, "b": 2}]'
>>> jj
'"[\\"abc\\", {\\"a\\": 1, \\"b\\": 2}]"'
>>> json.loads(j)
['abc', {'a': 1, 'b': 2}]
>>> json.loads(j) == obj
True
>>> json.loads(jj)
'["abc", {"a": 1, "b": 2}]'
>>> json.loads(jj) == j
True
>>> json.loads(jj) == obj
False

关于python - 类型错误 : string indices must be integers while parsing JSON using Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20084779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com