LoginSignup
12
1

【jq コマンド】JSON 要素をキー名でソートする

Last updated at Posted at 2021-04-24

jq コマンド1でソートをする際に、要素の「キー名」でソートしたい。

↓ これを

ソート前
{
  "Charlie": "tres",
  "Bravo": "dos",
  "Delta": "quatro",
  "Alfa": [
      "uno",
      "one"
  ]
}

↓ このようにソートしたい。

ソート後
{
  "Alfa": [
    "uno",
    "one"
  ],
  "Bravo": "dos",
  "Charlie": "tres",
  "Delta": "quatro"
}

「jq コマンド キー ソート」でググってもドンピシャの記事がなかったので自分のググラビリティとして。

TL; DR (今北産業)

  1. -S ショート・オプションを使う
  2. --sort-keys ロング・オプションを使う
  3. cat sample.json | jq -S . もしくは cat sample.json | jq --sort-keys .

TS; DR (キーでソートされた順序で各オブジェクトのフィールドを jq で出力する)

「jq コマンド キー ソート」でググってもも、なかなかタイトルからわかる記事がヒットしなかったのですが、公式のマニュアルに記載がありました。

  • --sort-keys / -S:

Output the fields of each object with the keys in sorted order.

(【筆者訳】キーでソートされた順序で各オブジェクトのフィールドを出力します。)
Invoking jq | jq Manual @ GitHub)

$ cat sample.json | jq -S .
{
  "Alfa": [
    "uno",
    "one"
  ],
  "Bravo": "dos",
  "Charlie": "tres",
  "Delta": "quatro"
}
  1. jq は JSON データ(要素やオブジェクト)を操作するためのコマンド・ツールです。Stephen Dolan 氏によって C 言語で書かれた軽量プログラムです。

12
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
1