linux下json文本解析工具:jq

前言

在linux环境下,对于json文本阅读是相当麻烦的,jq处理则相当轻松。

例子

使用测试内容data.json
[root@kilo-k5-controller baojx]# cat data.json
{
“char”: [“a”, “b”, “c”],
“data:info”: {
“bob”: {
“address”: “jiangsu-nanjing”,
“wage”: “10000”
},
“sam”: {
“address”: “jiangsu-taizhou”,
“wage”: “15000”
},
“rollyd”: {
“address”: “shanghai-jingan”,
“wage”: “20000”
}
}
}

  1. 获取整个json内容
    . 过滤器直接将json内容简单输出
    [root@kilo-k5-controller baojx]# cat data.json |jq .
    {
    “data:info”: {
    “rollyd”: {
    “wage”: “20000”,
    “address”: “shanghai-jingan”
    },
    “sam”: {
    “wage”: “15000”,
    “address”: “jiangsu-taizhou”
    },
    “bob”: {
    “wage”: “10000”,
    “address”: “jiangsu-nanjing”
    }
    },
    “char”: [
    “a”,
    “b”,
    “c”
    ]
    }

  2. 获取键"char"的值
    . 对指定键值过滤输出
    [root@kilo-k5-controller baojx]# cat data.json |jq .char
    [
    “a”,
    “b”,
    “c”
    ]

  3. 获取键值array中指定索引的数据
    .[]
    [root@kilo-k5-controller baojx]# cat data.json |jq .char[2]
    “c”

  4. 遍历键值array中所有数据
    .[]
    [root@kilo-k5-controller baojx]# cat data.json |jq .char[]
    “a”
    “b”
    “c”
    *输出三次

  5. 遍历字典(键值对)而非array
    5.1 遍历键值对输出效果同array遍历,不同的是输出数据仅为键值对中的value
    [root@kilo-k5-controller baojx]# cat data.json |jq .[]
    {
    “rollyd”: {
    “wage”: “20000”,
    “address”: “shanghai-jingan”
    },
    “sam”: {
    “wage”: “15000”,
    “address”: “jiangsu-taizhou”
    },
    “bob”: {
    “wage”: “10000”,
    “address”: “jiangsu-nanjing”
    }
    }
    [
    “a”,
    “b”,
    “c”
    ]
    5.2 对键值对遍历可以使用array指定索引类似的形式以获取指定key的vaule
    [root@kilo-k5-controller baojx]# cat data.json |jq ‘.[“char”]’
    [
    “a”,
    “b”,
    “c”
    ]
    *这种操作有一个最大的好处是,当key含有特殊字符串不能直接使用"."进行过滤输出时,可以用这种方法正常进行数据提取
    [root@kilo-k5-controller baojx]# cat data.json |jq ‘.data:info’
    error: syntax error, unexpected ‘:’, expecting $end
    .data:info
    ^
    1 compile error

[root@kilo-k5-controller baojx]# cat data.json |jq ‘.“data:info”’
error: syntax error, unexpected QQSTRING_START, expecting $end
.“data:info”
^
1 compile error

[root@kilo-k5-controller baojx]# cat data.json |jq ‘.[“data:info”]’
{
“rollyd”: {
“wage”: “20000”,
“address”: “shanghai-jingan”
},
“sam”: {
“wage”: “15000”,
“address”: “jiangsu-taizhou”
},
“bob”: {
“wage”: “10000”,
“address”: “jiangsu-nanjing”
}
}

  1. 筛选出address中jiangsu的键值对
    [root@kilo-k5-controller baojx]# cat data.json |jq ‘.[“data:info”][]|select(.address|contains(“jiangsu”))’
    {
    “wage”: “15000”,
    “address”: “jiangsu-taizhou”
    }
    {
    “wage”: “10000”,
    “address”: “jiangsu-nanjing”
    }

你可能感兴趣的:(Linux)