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.
Below is my code.
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)
So the first print(jsonStr) will print out something like this -
{"script":"#!/bin/bash\necho Hello world1\n"}
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
shell_script = j['script']
TypeError: string indices must be integers
So I am wondering what wrong I am doing here?
I have used same above code to parse the JSON and it works fine..
解决方案
Try replacing j = json.loads(json.dumps(jsonStr)) with j = json.loads(jsonStr).