壳解析JSON数据纵列 [英] Parsing Json data columnwise in shell
问题描述
当我运行一个命令,我得到这样的答复。
When I run a command I get a response like this
{
"status": "available",
"managed": true,
"name":vdisk7,
"support":{
"status": "supported"
},
"storage_pool": "pfm9253_pfm9254_new",
"id": "ff10abad"-2bf-4ef3-9038-9ae7f18ea77c",
"size":100
},
和数百个这种类型的列表或字典的
我想,做的事情,例如排序命令
and hundreds of this type of lists or dictionaries I want a command that does such sort of a thing
if name = "something",
get the id
任何链接,这将有助于我在学习这种排序的命令将是非常美联社preciated
Any links that would help me in learning such sort of commands would be highly appreciated
我曾尝试
的awk'{如果($ 2 ==东西)打印$ 0;}
awk '{if ($2 == "something") print $0;}'
但我认为,反应是用JSON所以聪明柱AWK格式是行不通的。
But I think the response is in Json so the colum wise awk formatting is not working.
此外,它只是一个简单的命令,我需要这样跑我会preFER不使用任何外部库。
Also it's just a single command that I need to run so I would prefer not to use any external library.
推荐答案
JSON解析器是完成这个任务更好
AWK
和 SED
的工具来分析面向行的文本,而不是JSON。如果你的JSON格式会改变什么? (一些行会在同一行?)。
awk
and sed
are utilities to parse line-oriented text, but not json. What if your json formatting will change ? (some lines will go on one line ?).
您应该使用任何标准JSON解析器在那里。或者使用一些功能强大的脚本语言,如PHP,Python和Ruby等。
You should use any standard json parser out there. Or use some powerful scripting language, such as PHP, Python, Ruby, etc.
我可以为您提供例如如何与蟒蛇去做。
I can provide you with example on how to do it with python.
如果我不能用强大的脚本语言?
如果你完全无法使用Python,再有就是效用 JQ
在那里:<一href=\"http://xmodulo.com/2013/05/how-to-parse-json-string-via-command-line-on-linux.html\">link
If you totally unable to use python, then there is utility jq
out there: link
如果你有最近的一些发行版, JQ
在仓库也许已经(例如:Ubuntu的13.10有它在回购)
If you have some recent distro, jq
maybe already in repositories (example: Ubuntu 13.10 has it in repos).
我可以使用Python!
我会做,使用简单的Python嵌入式脚本。
I would do that using simple python inline script.
例如,我们有一些 some_command
返回JSON作为结果。
For example we have some some_command
that returns json as a result.
我们必须让数据值[名称]
。
在这里,我们去:
some_command | python -c "import json, sys; print json.load(sys.stdin)['name']"
这将输出 vdisk7
你的情况
对于这个工作,你需要确定,JSON是完全有效的。
For this to work you need to be sure, json is fully valid.
如果您有JSON对象的列表:
If you have a list of json objects:
[
{
...
"name": "vdisk17"
...
},
{
...
"name": "vdisk18"
...
},
{
...
"name": "vdisk19"
...
},
...
]
您可以使用一些名单COM prehensions:
You could use some list comprehensions:
some_command | python -c "import json, sys; [sys.stdout.write(x['name'] + '\n') for x in json.load(sys.stdin)]"
这将输出:
vdisk17
vdisk18
vdisk19
这篇关于壳解析JSON数据纵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!