简体   繁体   English

如何在Linux上使用Python解析JSON字符串并打印出来?

[英]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. 这是一个非常基本的问题,但是我一点都不了解Python,我问你们。

I want to parse a JSON string on Linux command using Python . 我想using Python在Linux命令上解析JSON字符串。 and I want to print if only the value of the id column in the JSON string is "ok" . 并且我想打印如果只有JSON字符串中的id列的值为"ok"

For example, 例如,

extected (1) -> if id == ok 延伸(1)->如果id == ok
 $ echo '{"id": "ok", "name": "b"}' | python -c 'import json,sys; `blah blah blah.....' {"id": "ok", "name": "b"} 
extected (2) -> if id != ok 延伸(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. 所以我认为变量d是一个对象,而不是一个值。 So I tried to use read() . 所以我尝试使用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 TT 请帮我TT

You're right about d being an object. 您对d是一个对象是正确的。 You should output what was read in by json.parse instead: 您应该输出json.parse读入的json.parse

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) . 如果你想在标准JSON语法变化输出objjson.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). 您的第二个解决方案不起作用的原因是因为json.parse已经从stdin中读取了所有内容,而read()并没有重置流位置(stdin开始时是不可能的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM