python json解析 建索引,TypeError:使用Python解析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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值