【问题标题】:parse json with shell scripting at linux [duplicate]在linux上使用shell脚本解析json [重复]
【发布时间】:2011-04-24 14:25:33
【问题描述】:

可能重复:
Parsing json with sed and awk

我有一个如下例所示的 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,“驻留”:150,“虚拟”:76114,“支持”:true,“映射”:75950},“连接”:{“当前”:1,“可用”:9599},“extra_info”: { "note" : "字段因平台而异", "heap_usage_bytes" : 600592, "page_faults" : 1838 }, "indexCounters"....

【问题讨论】:

  • 鉴于json.org 中没有列出的 bash、csh、zsh、tcsh 等库 — 编写一个库并贡献它?
  • @Josh:你所有的编辑都属于我们。

标签: json shell


【解决方案1】:

您可以使用带有 json 模块的编程语言,或者如果您需要 shell+*nix 工具解决方案,您可以使用 awk

$ awk -F"[,:]" '{for(i=1;i<=NF;i++){if($i~/uptime\042/){print $(i+1)} } }' file
 527

【讨论】:

  • 在他的示例 json 中正常运行时间值正常。但不适用于 html 代码之类的值。
  • 这对我有用..谢谢
  • 如果我错了,请纠正我,您的示例中显示的是子字符串比较。在 if 循环中应该使用什么条件来检查 $i 是否等于正常运行时间。?
【解决方案2】:

使用 ruby​​ 的版本:

cat file | ruby -e "require 'rubygems'; require 'json'; puts JSON[STDIN.read]['serverStatus']['uptime'];"

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多