5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

jqコマンドをでやりたいことをやるサンプル集

Last updated at Posted at 2022-11-10

お仕事をしているとJSONを取り扱うことが良くあります。例えばAPIのレスポンスがJSONだったり、JSONファイルを取込んだりします。
そんなJSONを確認するためにちょっと加工したいこともよくあることです。
その時に便利なのがjqコマンドですが、使い方を忘れたとき用にサンプルやサイトのリンクを少しずつ書き溜めていきます。

参考になるサイト

配列の外と中の要素を並べてみたい

  • やりたいこと : 配列の外にある「out」と配列の中にある「aryIn1」「aryIn2」の値をCSVで横に並べてみたい
    • イメージ : "abcdefg","002","100"
sample.json
[
  {
    "out": "abcdefg",
    ...省略...
    "ary": [
      {
        "aryIn1": "002",
        "aryIn2": "100",
        ...省略...
      },
      {...省略...}
    ]
  },
  {...省略...}
]
  • jqでやる方法
    1. 一番外側の配列を抜出す : .[]
    2. 「out」「ary配列」を抜き出してオブジェクトにする : {out: .out, ary: .ary[]}
    3. 「out」と「ary配列の中のaryIn1とaryIn2」を抜出て配列にする : [.out, (.ary.aryIn1), (.ary.aryIn2)]
    4. CSV形式にする : @csv
    5. (必要であれば)リダイレクトしてファイルへ出力する : > out.csv
配列の外と中の要素を並べてみる
$ cat sample.json | jq -r '.[] | {out: .out, ary: .ary[]} | [.out, (.ary.aryIn1), (.ary.aryIn2)] | @csv'
"abcdefg","002","100"
"abcdefg","002","685"
"abcdefg","030","687"
"abcdefg","030","841"
"abcdefg","030","028"
"skrdfgu","030","687"
"skrdfgu","030","841"
"skrdfgu","030","028"
...
5
0
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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?