jq 指令超實用秘訣
Posted on May 21, 2020 in Unix-like 命令列教學 by Amo Chen ‐ 2 min read
談到透過命令列處理 JSON ,直覺就會想到 jq 。
近來學會利用 jq 指令處理 JSON 資料後透過樣板(template)輸出格式化字串,因此本篇將分享 2 個關於 jq 的實用秘訣:
|運算子(operator)- 輸出 jq 結果到 standard output (stdout)
本文環境
- jq 1.4
- macOS 10.15
| 運算子(operator)
jq 可以很快地取得 JSON 資料中的特定欄位值,例如:
$ echo '{"foo": {"bar": 1}}' | jq '.foo.bar'
1
但是 jq 其實還可以透過 | 運算子將資料丟進樣板中再輸出:
$ echo '{"foo": {"bar": 1}}' | jq '.foo.bar | tostring | "foo.bar=" + .'
"foo.bar=1"
上述範例我們透過 | 運算子將 bar 的值先轉成字串後,在丟到 "foo.bar=" + . 樣板中,將 foo.bar= 與 bar 的值透過 + 將 2 個字串結合在一起後輸出。
. 就是 bar 的值,如果你有多個欄位想一併輸出可以用 .欄位 的方式取得該欄位的值,例如:
$ echo '{"foo": {"a": "1", "b": "2"}}' | jq '.foo | "a=" + .a + " b=" + .b'
"a=1 b=2"
但是上述輸出的結果仍不盡理想,因為 jq 自動幫我們加上 " 包住輸出結果,如果我們想再運用其他指令處理 jq 的輸出結果就又得移除 " 。
然而解決方法其實很簡單,只要讓 jq 使用標準輸出即可。
輸出 jq 結果到 standard output (stdout)
要讓 jq 使用標準輸出(standard output, stdout) 其實很簡單,只要加上 -r 參數即可:
$ echo '{"foo": {"bar": 1}}' | jq -r '.foo.bar | tostring | "foo.bar=" + .'
foo.bar=1
-r 其實就代表 --raw-output , jq 就會將 " 去除。
With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.
以上就是本篇分享的 jq 超實用秘訣!
Happy Coding!
References
https://stedolan.github.io/jq/