user3508811
user3508811

Reputation: 925

how to parse a JSON output?

I am trying to parse the output a command which is in JSON format and running into below error?I provided a sample output of the command aswell,any pointers on how to fix it?

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"]

OUTPUT:-

{"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":"[email protected]","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}

ERROR:-

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

Upvotes: 0

Views: 1531

Answers (1)

Neapolitan
Neapolitan

Reputation: 2163

Need to convert the string into json, like the following:

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

To access the first one:

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

Upvotes: 2

Related Questions