soy
soy

Reputation: 143

How can I parse JSON string and print it using Python on linux?

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

Upvotes: 0

Views: 1228

Answers (1)

PeteyPii
PeteyPii

Reputation: 379

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).

Upvotes: 1

Related Questions