RHEL9 jsonコマンドでjsonデータから特定要素を取得するサンプル

環境
Red Hat Enterprise Linux release 9.2 (Plow)

操作方法
1.jqコマンドのインストール
$ sudo dnf -y install epel-release
$ sudo dnf -y install jq

2.バージョンを確認する
$jq –version
jq-1.6
3.jsonファイルを作成します
test.json

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"total_count": 3,
"items": [
{
"id": 111,
"name": "yamada",
"owner": {
"id": 1001,
"type": "tokyo"
},
"size": 10
},
{
"id": 2002,
"name": "oosaki",
"owner": {
"id": 2002,
"type": "oosaka"
},
"size": 30
},
{
"id": 3003,
"name": "hashimoto",
"owner": {
"id": 3003,
"type": "yokohama"
},
"size": 25
}
]
}
{ "total_count": 3, "items": [ { "id": 111, "name": "yamada", "owner": { "id": 1001, "type": "tokyo" }, "size": 10 }, { "id": 2002, "name": "oosaki", "owner": { "id": 2002, "type": "oosaka" }, "size": 30 }, { "id": 3003, "name": "hashimoto", "owner": { "id": 3003, "type": "yokohama" }, "size": 25 } ] }
{
  "total_count": 3,
  "items": [
    {
      "id": 111,
      "name": "yamada",
      "owner": {
        "id": 1001,
        "type": "tokyo"
      },
      "size": 10
    },
    {
      "id": 2002,
      "name": "oosaki",
      "owner": {
        "id": 2002,
        "type": "oosaka"
      },
      "size": 30
    },
    {
      "id": 3003,
      "name": "hashimoto",
      "owner": {
        "id": 3003,
        "type": "yokohama"
      },
      "size": 25
    }
  ]
}

操作例
1.特定要素を取得する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$cat test.json | jq '.total_count'
3
$cat test.json | jq '.total_count' 3
$cat test.json | jq '.total_count'
3

2.配列内の特定要素を取得する
items配列 の全要素から、id の値を取得します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$cat test.json | jq '.items[].id'
111
2002
3003
$cat test.json | jq '.items[].id' 111 2002 3003
$cat test.json | jq '.items[].id'
111
2002
3003

items配列 の1番目の要素の id の値を取得します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$cat test.json | jq '.items[0].id'
111
$cat test.json | jq '.items[0].id' 111
$cat test.json | jq '.items[0].id'
111

3.配列の要素数を取得します。
$ cat test.json | jq '[.items[]] | length’
3

4.ダブルクォートを取り除きます

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$cat test.json | jq '.items[].name'
"yamada"
"oosaki"
"hashimoto"
$cat test.json | jq '.items[].name' "yamada" "oosaki" "hashimoto"
$cat test.json | jq '.items[].name'
"yamada"
"oosaki"
"hashimoto"

-rオプション を利用すると、ダブルクォートが取り除かれます

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$cat test.json | jq -r '.items[].name'
yamada
oosaki
hashimoto
$cat test.json | jq -r '.items[].name' yamada oosaki hashimoto
$cat test.json | jq -r '.items[].name'
yamada
oosaki
hashimoto

 

IT

Posted by arkgame