jq

jqの基本的な使い方

More than 3 years have passed since last update.


対象データ


sample.json

{"menu": {

"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}

※参照元: JSON Example


目的別コマンド例

全てを表示

$ cat sample.json | jq "."

{
"menu": {
"popup": {
"menuitem": [
{
"onclick": "CreateNewDoc()",
"value": "New"
},
{
"onclick": "OpenDoc()",
"value": "Open"
},
{
"onclick": "CloseDoc()",
"value": "Close"
}
]
},
"value": "File",
"id": "file"
}
}

menuの中身表示

$ cat sample.json | jq ".menu"

{
"popup": {
"menuitem": [
{
"onclick": "CreateNewDoc()",
"value": "New"
},
{
"onclick": "OpenDoc()",
"value": "Open"
},
{
"onclick": "CloseDoc()",
"value": "Close"
}
]
},
"value": "File",
"id": "file"
}

menuitemの0番目の中身表示

$ cat sample.json | jq ".menu.popup.menuitem[0]"

{
"onclick": "CreateNewDoc()",
"value": "New"
}

menuitemの0番目のvalueを表示

$ cat sample.json | jq ".menu.popup.menuitem[0].value"

"New"

menuitemの全ての要素のvalueを表示

$ cat sample.json | jq ".menu.popup.menuitem[].value"

"New"
"Open"
"Close"