Linux 下使用 jq 命令行下解析处理 json 文件

介绍

jq 是 Linux 中处理 json 的强大工具,使用文档参考:https://stedolan.github.io/jq/manual/.

安装部署

yum

yum install jq

源码

cd /usr/local/bin/
wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux32 (32-bit system)
wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 (64-bit system)
mv jq-linux32 jq
mv jq-linux64 jq
chmod +x ./jq

下载地址:https://stedolan.github.io/jq/download/

示例

json样本文件:

cat google.json  
{
        "name": "Google",
        "location":
                {
                        "street": "1600 Amphitheatre Parkway",
                        "city": "Mountain View",
                        "state": "California",
                        "country": "US"
                },
        "employees":
                [
                        {
                                "name": "Michael",
                                "division": "Engineering"
                        },
                        {
                                "name": "Laura",
                                "division": "HR"
                        },
                        {
                                "name": "Elise",
                                "division": "Marketing"
                        }
                ]
}

{}括起来的是对象,如果是[]括起来的就是数组了。

使用

获取对象

cat google.json | jq '.name'
"Google"

获取嵌套对象

cat google.json | jq '.location.city'
"Mountain View"

获取一个数组的值

cat google.json | jq '.employees[0].name'
"Michael"

获取对象的多个字段

cat google.json | jq '.location | {street, city}'
{
  "city": "Mountain View",
  "street": "1600 Amphitheatre Parkway"
}

示例

curl 和 jq 示例

curl -s ... | jq .

如果返回的是一个字符串,不想要字符串的引号,-r即可

curl -s ... | jq '.location.city'
"Mountain View"
curl -s ... | jq -r '.location.city'
Mountain View

如果要计算某个数组的长度,length:

curl -s ... | jq '.data | length'

获取 k8s 示例

kubectl get pod server-5b594c7779-54vs4 -o json |  jq '.apiVersion'
[root@xiexianbin_cn ~]# kubectl get pod server-5b594c7779-54vs4 -o json |  jq '.status.conditions'
[
  {
    "lastProbeTime": null,
    "lastTransitionTime": "2018-03-05T11:16:45Z",
    "status": "True",
    "type": "Initialized"
  },
  {
    "lastProbeTime": null,
    "lastTransitionTime": "2018-03-05T11:16:55Z",
    "status": "True",
    "type": "Ready"
  },
  {
    "lastProbeTime": null,
    "lastTransitionTime": "2018-03-05T11:16:45Z",
    "status": "True",
    "type": "PodScheduled"
  }
]
[root@xiexianbin_cn ~]# kubectl get pod server-5b594c7779-54vs4 -o json |  jq '.status.conditions | length'
3
[root@xiexianbin_cn ~]# kubectl get pod server-5b594c7779-54vs4 -o json |  jq '.status.conditions[0].lastTransitionTime'
"2018-03-05T11:16:45Z"
[root@xiexianbin_cn ~]# 

完毕。