如何解析JSON输出?

时间:2016-12-06 01:34:54

标签: python json

我试图解析输出一个JSON格式的命令并运行到下面的错误?我提供了命令的示例输出,以及如何解决它的任何指针?

import subprocess,json
user = 'user1'
gerrit = '1234567'
branch_cmd = "ssh -l %s -p 29418 review-android.quicinc.com gerrit query %s --format=JSON"%(user,gerrit)
proc = subprocess.Popen(branch_cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error) = proc.communicate()
print output["branch"]

输出: -

{"project":"platform/system/technology","branch":"technology.lnx.2.1-dev","topic":"","id":"Id1ca6a5167c8e7269b154824e5a5dd2389a2d1cf","number":"1234567","subject":"Bluetooth:HOGP Write Scan Interval Window characteristic","owner":{"name":"Firstname Kumar name","email":"sname@sub.comp.com","username":"sname"},"url":"https://review-android.company.com/1234567","createdOn":1471052441,"lastUpdated":1480706360,"sortKey":"004195870019d68b","open":false,"status":"ABANDONED"}
{"type":"stats","rowCount":1,"runTimeMilliseconds":1}

错误: -

  File "strip_dev_rel.py", line 10, in <module>
    print output["branch"]
TypeError: string indices must be integers, not str

1 个答案:

答案 0 :(得分:2)

需要将字符串转换为json,如下所示:

for line in output.split('\n'):
    print json.loads(line)

要访问第一个:

line1 = output.split('\n')[0]
print json.loads(line)["branch"]