jqコマンドを利用して検索をまとめる

jqコマンドを利用して検索をまとめる

Twitter LINEで送る Facebook はてなブログ

jqコマンドのインストール Mac

brew install jq

サンプル用のjsonデータ

data.json

{
	"entities": [
		{
			"id": 1,
			"title": "タイトル1",
			"description": "タイトルの説明文",
			"tags": [
				"json",
				"jq"
			],
			"created_at": "2024-04-02 12:15",
			"updated_at": "2024-04-02 12:15"
		},
		{
			"id": 2,
			"title": "Title 2",
			"description": "Title 2の説明文",
			"tags": [
				"data",
				"jq"
			],
			"created_at": "2024-04-30 10:12",
			"updated_at": "2024-04-02 12:15"
		},
		{
			"id": 9,
			"title": "Subject 3",
			"description": "Subject 3の説明文",
			"tags": [
				"queue",
				"message"
			],
			"created_at": "2023-01-29 23:49",
			"updated_at": "2024-04-02 12:15"
		}
	],
	"page": 1,
	"next": null
}

基本のjqコマンド

cat data.json | jq

基本的にはこの後にいろいろオプションを指定して検索をしていきます。

jsonの中から配列を指定して一覧を取得

cat data.json |  jq  '.entities'

実行結果

[
  {
    "id": 1,
    "title": "タイトル1",
    "description": "タイトルの説明文",
    "tags": [
      "json",
      "jq"
    ],
    "created_at": "2024-04-02 12:15",
    "updated_at": "2024-04-02 12:15"
  },
  {
    "id": 2,
    "title": "Title 2",
    "description": "Title 2の説明文",
    "tags": [
      "data",
      "jq"
    ],
    "created_at": "2024-04-30 10:12",
    "updated_at": "2024-04-02 12:15"
  },
  {
    "id": 9,
    "title": "Subject 3",
    "description": "Subject 3の説明文",
    "tags": [
      "queue",
      "message"
    ],
    "created_at": "2023-01-29 23:49",
    "updated_at": "2024-04-02 12:15"
  }
]

entitiesの一覧を取得できます。

jsonの中の配列からtitleのみを取得する

cat data.json |  jq  '.entities.[].title'

実行結果

"タイトル1"
"Title 2"
"Subject 3"

事項結果がシンプルになりました。 タイトルのみを取得する形なので検索が簡単になります。

jsonの配列から特定の項目のみに絞る

cat data.json |  jq  '.entities.[] | {"title": .title, "desc": .description}'

実行結果

{
  "title": "タイトル1",
  "desc": "タイトルの説明文"
}
{
  "title": "Title 2",
  "desc": "Title 2の説明文"
}
{
  "title": "Subject 3",
  "desc": "Subject 3の説明文"
}

タイトルと、descriptionをdescと言う名称に変換して取得する方法です。

jsonの多数の配列の要素たちを取得

cat data.json |  jq  '.entities.[].tags'

実行結果

[
  "json",
  "jq"
]
[
  "data",
  "jq"
]
[
  "queue",
  "message"
]

今回の場合はtagsの一覧を取得するようにしてみました。

正規表現を利用

cat data.json |  jq  '.entities.[] | select(.tags[] | test("(jq|json)"))'

実行結果

{
  "id": 1,
  "title": "タイトル1",
  "description": "タイトルの説明文",
  "tags": [
    "json",
    "jq"
  ],
  "created_at": "2024-04-02 12:15",
  "updated_at": "2024-04-02 12:15"
}
{
  "id": 2,
  "title": "Title 2",
  "description": "Title 2の説明文",
  "tags": [
    "data",
    "jq"
  ],
  "created_at": "2024-04-30 10:12",
  "updated_at": "2024-04-02 12:15"
}

とりあえず自分が必要としているものをまとめました。