TypeError:使用Python解析JSON时,字符串索引必须是整数? [英] TypeError: string indices must be integers while parsing JSON using Python?
问题描述
我现在感到困惑,为什么我无法解析此JSON字符串.类似的代码可以在其他JSON字符串上正常工作,但不能在此字符串上正常工作-我正在尝试解析JSON字符串并从JSON提取脚本.
I am confuse now why I am not able to parse this JSON string. Similar code works fine on other JSON string but not on this one - I am trying to parse JSON String and extract script from the 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)
将打印出这样的内容-
So the first print(jsonStr)
will print out something like this -
{"script":"#!/bin/bash\necho Hello world1\n"}
第二个print(j)
将打印出类似这样的内容-
And the second print(j)
will print out something like this -
{"script":"#!/bin/bash\necho Hello world1\n"}
然后没有打印出第三张照片,它给出了此错误-
And then the third print doesn't gets printed out and it gives this error -
Traceback (most recent call last):
File "test5.py", line 33, in <module>
shell_script = j['script']
TypeError: string indices must be integers
所以我想知道我在这里做错什么了吗?
So I am wondering what wrong I am doing here?
我已经使用了与上面相同的代码来解析JSON,并且效果很好.
I have used same above code to parse the JSON and it works fine..
推荐答案
尝试将j = json.loads(json.dumps(jsonStr))
替换为j = json.loads(jsonStr)
.
这篇关于TypeError:使用Python解析JSON时,字符串索引必须是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!