0

This is a pretty basic question, but I don't know Python at all and I ask you guys.

I want to parse a JSON string on Linux command using Python. and I want to print if only the value of the id column in the JSON string is "ok".

For example,

extected (1) -> if id == ok
$ echo '{"id": "ok", "name": "b"}' | python -c 'import json,sys; `blah blah blah.....'

{"id": "ok", "name": "b"}
extected (2) -> if id != ok
$ echo '{"id": "no", "name": "a"}' | python -c 'import json,sys; `blah blah blah.....'
(empty)

I tried many attempts to solve this problem, but all failed..

echo '{"id":"ok", "name": "a"}' | python -c 'import json,sys; d=sys.stdin; obj=json.load(d); print (d if obj["id"] == "ok" else "")'
<open file '<stdin>', mode 'r' at 0x7fb6391060c0>

So I thought variable d is an object, not a value. So I tried to use read().

echo '{"id":"ok", "name": "a"}' | python -c 'import json,sys; d=sys.stdin; obj=json.load(d); print (d.read() if obj["id"] == "ok" else "")'
(empty)

I don't know understand why nothing is printed..

Please help me T.T

0

1 Answer 1

1

You're right about d being an object. You should output what was read in by json.parse instead:

echo '{"id":"ok", "name": "a"}' | python -c 'import json,sys; d=sys.stdin; obj=json.load(d); print (obj if obj["id"] == "ok" else "")'

If you want the output in standard JSON syntax change obj to json.dumps(obj).

The reason your second solution does not work is because json.parse already read all the contents from stdin and read() does not reset the stream position (which is not possible for stdin to begin with).

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, thank you.. echo '{"id":"ok", "name": "a"}' | python -c 'import json,sys; d=sys.stdin; obj=json.load(d); print (json.dumps(obj) if obj["id"] == "ok" else "")' works well XD

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.