Shell处理json数据

Shell处理json数据的方法,简单介绍一下,本文基于CentOS 6 64bit。

yum install jq    #需要EPEL源

下面我们有一个config.json文件

{
  "USERNAME": "admin",
  "CLUSTERMAP_HOSTS": {
      "staging":{
          "pc": "10.191.130.70",
          "app": "10.191.76.250",
          "wx": "172.28.172.171"
      },
      "production":{
          "mjq_pc":"172.28.139.30",
          "mjq_app":"172.28.148.150",
          "mjq_weixin":"172.28.149.84",
          "mjq_qq":"172.28.149.77",
          "lf_pc":"172.20.145.51",
          "lf_app":"172.20.145.40",
          "lf_weixin":"172.20.145.86",
          "lf_qq":"172.20.112.150",
          "jos":"172.20.145.50",
          "lf_coupon":"172.20.112.44",
          "mjq_coupon":"172.28.139.48"
      },
      "ab":{
          "mjq_pc":"172.28.175.36",
          "lf_app":"172.20.121.107"
      }
  },
  "CLUSTERMAP_BINARY_PATH": "/export/App/jd_search/clustermap/bin"
}

获得分片

$ cat config.json | jq '.CLUSTERMAP_HOSTS.production'
[
  {
    "lf_app": "172.20.121.107",
    "mjq_pc": "172.28.175.36"
  },
  {
    "mjq_coupon": "172.28.139.48",
    "lf_coupon": "172.20.112.44",
    "jos": "172.20.145.50",
    "mjq_pc": "172.28.139.30",
    "mjq_app": "172.28.148.150",
    "mjq_weixin": "172.28.149.84",
    "mjq_qq": "172.28.149.77",
    "lf_pc": "172.20.145.51",
    "lf_app": "172.20.145.40",
    "lf_weixin": "172.20.145.86",
    "lf_qq": "172.20.112.150"
  },
  {
    "wx": "172.28.172.171",
    "app": "10.191.76.250",
    "pc": "10.191.130.70"
  }
]

获得Key列表

$ cat config.json | jq '.CLUSTERMAP_HOSTS.production | keys'
[
  "jos",
  "lf_app",
  "lf_coupon",
  "lf_pc",
  "lf_qq",
  "lf_weixin",
  "mjq_app",
  "mjq_coupon",
  "mjq_pc",
  "mjq_qq",
  "mjq_weixin"
]

获得某个key下面的所有value(列表形式)

$ cat config.json | jq '[ .CLUSTERMAP_HOSTS.production[] ]'
[
  "172.28.139.48",
  "172.20.112.44",
  "172.20.145.50",
  "172.28.139.30",
  "172.28.148.150",
  "172.28.149.84",
  "172.28.149.77",
  "172.20.145.51",
  "172.20.145.40",
  "172.20.145.86",
  "172.20.112.150"
]

获得某个key下面的所有value(文本形式)

$ cat config.json | jq ' .CLUSTERMAP_HOSTS.production[] '
"172.28.139.48"
"172.20.112.44"
"172.20.145.50"
"172.28.139.30"
"172.28.148.150"
"172.28.149.84"
"172.28.149.77"
"172.20.145.51"
"172.20.145.40"
"172.20.145.86"
"172.20.112.150"

获得某个key(含多个子key)下面的所有(子key)的value(文本形式)

$ jq '.CLUSTERMAP_HOSTS[][]' jd_search_opcenter/opcenter/config.json 
"172.20.121.107"
"172.28.175.36"
"172.28.139.48"
"172.20.112.44"
"172.20.145.50"
"172.28.139.30"
"172.28.148.150"
"172.28.149.84"
"172.28.149.77"
"172.20.145.51"
"172.20.145.40"
"172.20.145.86"
"172.20.112.150"
"172.28.172.171"
"10.191.76.250"
"10.191.130.70"

参考文档:
jq : Linux下json的命令行工具
jq parsing get value

发表评论

您的电子邮箱地址不会被公开。