当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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 server-name.com 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":"[email protected]","username":"user1"},"url":"https://server-name.com/1857599","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/__init__.py", line 338, in loads

return _default_decoder.decode(s)

File "/usr/lib/python2.7/json/decoder.py", line 366, in decode

obj, end = self.raw_decode(s, idx=_w(s, 0).end())

TypeError: expected string or buffer

网友答案:

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:

json.loads(op[0])
网友答案:

Your op variable returned from subprocess is not a string, it is a tuple of 2 elements. Just do: js = json.loads(op[0]) instead, to parse the first element, which is the json string you are attempting to parse

分享给朋友:
您可能感兴趣的文章:
随机阅读: