簡介
jq 是一個基於命令列的 JSON 處理器。
安裝
使用 brew 指令安裝。
| 1 | brew install jq | 
確認版本。
| 1 | jq --version | 
使用
標準輸入輸出
例如,使用 curl 指令取得 jq 儲存庫的前 5 筆 commit 資料。
| 1 | curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | 
使用 | 符號將資料傳遞給 jq 指令,使用 . 符號表示原封不動地輸出。
| 1 | curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \ | 
取得第一筆 commit 資料。
| 1 | curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \ | 
取得第一筆 commit 資料中的指定欄位。
| 1 | curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \ | 
取得每一筆 commit 資料中的指定欄位,jq 會以串流方式輸出。
| 1 | curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \ | 
取得每一筆 commit 資料中的指定欄位,並放到單一陣列中輸出。
| 1 | curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \ | 
檔案
假設有以下 example.json 檔,jq 指令也可以對檔案進行操作。
| 1 | { | 
使用 jq 的 del 方法,輸出一個經過欄位刪減的結果,原來的檔案並不會被更動。
| 1 | jq 'del(.[]["name"])' example.json | 
輸出結果如下。
| 1 | { | 
將結果存成另一個檔案。
| 1 | jq 'del(.[]["name"])' example.json >> example2.json |