Krish Krish - 1 year ago 103
JSON Question

Parsing a json output string

I am new to Python, How to convert this to a json string? I like to get the first line of the commitMessage in below output(op) ? thanks in advance

>>> op = subprocess.Popen('ssh -p 29999 gerrit query --commit-message --format=JSON Ib3856dcf0826942787c3d5a076eb6888dae9k2be', shell=True, stdout=subprocess.PIPE, cwd='../').communicate()
>>> op
('{"project":"mtt/proprietary/fg","branch":"master","id":"Ib3856dcf0826942787c3d5a076eb6888dae9k2be","number":"1857599","subject":"store Gain","owner":{"name":"owner1","email":"","username":"user1"},"url":"","commitMessage":"my commit message\\n\\nChange-Id: Ib949999d3f4d94299993d5a076eb681c4aaaa2be\\n","createdOn":1478281199,"lastUpdated":1478732989,"sortKey":"0041150d001ad179","open":false,"status":"MERGED"}\n{"type":"stats","rowCount":1,"runTimeMilliseconds":4}\n', None)
>>> js = json.loads(op)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

Answer Source

Processes have two standard output streams: stdout and stderr. One for regular output and other for errors. communicate returns a tuple with two elements: first is stdout and second is stderr. You need the first:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download