jq 一个强悍的json格式化查看工具

本文来自网易云社区


作者:娄超

在web 2.0时代json这种直观、灵活、高效数据格式基本已经成为一种标准格式,从各种web api,到配置文件,甚至现在连mysql都开始支持json作为数据类型。

但是在平时开发运维中往往因为格式问题或者输出数据太多,体验不是很爽,之前我就经常需要借助一些json自动语法检查、格式化、分层折叠的工具(如http://www.bejson.com/ ), 往往还是需要来回拷贝,还是觉得很麻烦。

所以,一直希望有个linux命令行的简单命令(python的json.tool模块只能格式化显示),偶然发现了这个jq的小工具,感觉很强大,就分享一下。

不说废话了,直接例子说明吧

使用说明

1、格式化json数据

echo '{"kind": "Service", "apiVersion": "v1", "status": {"loadBalancer": true}}'|jq .{  "kind": "Service",  "apiVersion": "v1",  "status": {    "loadBalancer": true
  }}

只要3个字母搞定,其中jq是工具命令,后面参数是过滤选择参数,"." 表示直接输出完整的json数据。

Usage: jq [options]  [file...]

2. 过滤出需要的字段信息

cat service.json
{    "kind": "Service",    "apiVersion": "v1",    "metadata": {        "name": "kubernetes",        "namespace": "default",
    },    "spec": {        "ports": [
            {                "protocol": "TCP",                "port": 443,                "targetPort": 443,                "nodePort": 0
            }
        ],
.....很多数据
}
cat service.json|jq .metadata.name"kubernetes"

3、过滤出某个数组对象

cat service.json|jq .spec.ports[0]  
{  "protocol": "TCP",  "port": 443,  "targetPort": 443,  "nodePort": 0}

4、使用管道过滤并调整输出

cat service.json|jq  ".spec.ports[0]| {srcPort: .port, targetPort: .targetPort}"    {  "srcPort": 443,  "targetPort": 443}

如果数据的下标为不填,将输出所有数组的过滤值,如 cat service.json|jq ".spec.ports[]| {srcPort: .port, targetPort: .targetPort}"

5、 自定义输出数组

cat t.json
{  "parents": [
    {      "sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",      "url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",      "html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"
    },
    {      "sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",      "url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",      "html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"
    }
  ]
}
cat t.json|jq ' { html_urls: [.parents[].html_url]}'{  "html_urls": [    "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7",    "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"
  ]
}

6、支持条件查询

举个简单例子,只输出tcp协议端口信息

cat service.json|jq .spec.ports[0]  
{  "protocol": "TCP",  "port": 443,  "targetPort": 443,  "nodePort": 0}cat service.json |jq 'if .spec.ports[0].protocol = "tcp" then .spec.ports[0] else "not tcp" end'

注意jq 的语法有点奇怪, 必须 if else 同时存在,数字相等是用 "==",字符串是"="

总之,jq 功能是很强大的,它是一个c语言写的小工具,包括很多正则匹配,更多高级使用方法,见 https://stedolan.github.io/jq/manual/

安装说明

Debian and Ubuntu 下