一.使用 python -m json.tool
cat test.json | python -m json.tool
二.jq格式化
在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 下 sudo apt-get install jq OS X 下 brew install jq CentOs yum install -y jq 源碼安裝 git clone https://github.com/stedolan/jq.git cd jq autoreconf -i ./configure --disable-maintainer-mode make sudo make install
windows下也可以直接下載,但是沒用過。 詳細見https://stedolan.github.io/jq/download/
