Shell处理json数据的方法,简单介绍一下,本文基于CentOS 7 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/helloworld/clustermap/bin"
}
获得某1个key的value
$ jq '.CLUSTERMAP_HOSTS.production' config.json
{
"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"
}
$ jq '.CLUSTERMAP_HOSTS.production.mjq_pc' config.json
"172.28.139.30"
获得某些(多个)key的value
$ jq '.CLUSTERMAP_HOSTS | .production, .ab' config.json
{
"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"
}
{
"mjq_pc": "172.28.175.36",
"lf_app": "172.20.121.107"
}
获得key列表