0

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
2
  • 1
    op is a tuple, perhaps you meant json.loads(op[0]) Commented Nov 16, 2016 at 17:37
  • Try this json.loads(json.dumps(op)) Commented Nov 16, 2016 at 18:14

2 Answers 2

4

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])
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, I get error raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 2 column 1 - line 3 column 1 (char 597 - 651) any idea?
Your json is not valid. Comma is missing before {"type":"stats",
yes \n{"type":"stats","rowCount":1,"runTimeMilliseconds":2}\n is the second item in the gerrit query output, checking how to make gerrit query stop printing that, or can I make python to ignore it?
op = op[0].split('\n')[0] did it, :), dirty ?
No, not dirty. You need the first line and this code does exactly that.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.