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

标签 python json parsing

我现在很困惑为什么我不能解析这个 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/

相关文章:

python - 张量数组 TensorArray_1_0 : Could not read from TensorArray index 0 because it has not yet been written to

javascript - 使用函数名称将 JSON 字符串解析为 JavaScript 对象

string - 验证 NSTextField 中的字符串是否为有效的 IP 地址或域名

java - 为什么 12 :20 PM parse to 0:20 on the next day?

python - 这个Python列表理解表达式可以简化吗?

python - Pipenv 始终无法锁定并产生大量错误输出

python - 基于列值的 GroupBy 和 Shift

python - 我有单元素数组。如何将它们更改为元素本身?

javascript - Jasmine: stub ajax 成功调用并向函数传递参数

java - 在Java中加载和显示HTML+CSS