"metadata":{"name":"kubernetes"
标签:
jq 一个强悍的json格局化检察工具https://
在web 2.0时代json这种直不雅观、灵活、高效数据格局根基已经成为一种标准格局,从各类web api,到配置文件,甚至此刻连mysql都开始撑持json作为数据类型。
但是在平时开发运维中往往因为格局问题或者输出数据太多,体验不是很爽,之前我就经常需要借助一些json自动语法查抄、格局化、分层折叠的工具(如 ), 往往还是需要来回拷贝,还是感受很麻烦。
所以,一直但愿有个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 下
[转帖]jq 一个强悍的json格局化检察工具
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31453.html