在 linux 上使用 shell 脚本解析 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3919750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parse json with shell scripting at linux
提问by srknc
Possible Duplicate:
Parsing json with sed and awk
可能的重复:
使用 sed 和 awk 解析 json
I have a JSON string like the example below and I want to use, for example, the value of the "uptime" command as a variable in a shell script, what should I do?
我有一个如下例所示的 JSON 字符串,我想使用例如“uptime”命令的值作为 shell 脚本中的变量,我该怎么办?
{ "serverStatus" : { "version" : "1.6.0", "uptime" : 527, "uptimeEstimate" : 526, "localTime" : { "$date" : 1286923624579 }, "globalLock" : { "totalTime" : 526604302, "lockTime" : 3499842, "ratio" : 0.006646056605895331, "currentQueue" : { "total" : 0, "readers" : 0, "writers" : 0 } }, "mem" : { "bits" : 64, "resident" : 150, "virtual" : 76114, "supported" : true, "mapped" : 75950 }, "connections" : { "current" : 1, "available" : 9599 }, "extra_info" : { "note" : "fields vary by platform", "heap_usage_bytes" : 600592, "page_faults" : 1838 }, "indexCounters"....
{“serverStatus”:{“version”:“1.6.0”,“uptime”:527,“uptimeEstimate”:526,“localTime”:{“$date”:1286923624579},“globalLock”:{“totalTime”: 526604302, "lockTime" : 3499842, "ratio" : 0.006646056605895331, "currentQueue" : { "total" : 0, "readers" : 0, "writers" : 0 } }, "mem" : { “居民”:150,“虚拟”:76114,“支持”:真,“映射”:75950},“连接”:{“当前”:1,“可用”:9599},“额外信息”:{“注意” " : "字段因平台而异", "heap_usage_bytes" : 600592, "page_faults" : 1838 }, "索引计数器”....
回答by ghostdog74
You can use a programming language with a json module, or if you desire a shell+*nix tool solution, you can use awk
您可以使用带有 json 模块的编程语言,或者如果您需要 shell+*nix 工具解决方案,您可以使用 awk
$ awk -F"[,:]" '{for(i=1;i<=NF;i++){if($i~/uptime2/){print $(i+1)} } }' file
527
回答by boecko
Version which uses ruby:
使用 ruby 的版本:
cat file | ruby -e "require 'rubygems'; require 'json'; puts JSON[STDIN.read]['serverStatus']['uptime'];"

