13
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【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 言語で書かれた軽量プログラムです。

13
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
13
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?