テストデータ
data.json
{
"companyName" : "MyCompany,inc",
"contact": {
"phone" : "00-0000-0000",
"email" : "foo@example.com",
"address" : "xxx xxxx xxxx 3F"
},
"employees" : [
{
"id":1,
"name": "Alice",
"address": "aaa aaa aaa"
},
{
"id":2,
"name": "Bob",
"address": "bbb bbb bbb"
},
{
"id":3,
"name": "Carol",
"address": "ccc ccc ccc"
}
]
}
json全体を表示
cat data.json | jq
任意のキーの要素を表示
cat data.json | jq .employees
キー名を表示
cat data.json | jq 'keys'
配列の要素数を表示
cat data.json | jq '.employees | length'
配列の特定の値のみ表示
cat data.json | jq '.employees[].name'
範囲選択
すべて
cat data.json | jq '.employees[]'
先頭
cat data.json | jq '.employees[0]'
末尾
cat data.json | jq '.employees[-1]'
範囲
cat data.json | jq '.employees[1:3]'
指定した要素で新しいオブジェクトを作成
cat data.json | jq '.employees[] | {id:.id,name:.name}'
指定した要素で新しい配列を作成
cat data.json | jq '.employees[] | [.id,.name]'
cat data.json | jq '.employees[] | [.id,.name] | @csv'
フィルタ
cat data.json | jq '.employees[] | select(.id>=2)'
参考
https://programminghistorian.org/en/lessons/json-and-jq
https://gist.github.com/olih/f7437fb6962fb3ee9fe95bda8d2c8fa4