LoginSignup
2
2

jq tips

Last updated at Posted at 2022-11-11

json の任意の階層の特定キーの値を取り出す

$ cat sample.json
{
  "level1key":{
    "level2key":{
      "level3key":{
        "level4key":"level4value"
      }
    }
  }
}

$ jq "..|.level4key?|select(.!=null)" sample.json
"level4value"

特定のキー名を持つ要素を取り出す

上の記事を参考に

1階層下で "/" で始まるキー名を持つ要素について、xxx のキー名で配列の中身がない要素を抽出する。

jq 'to_entries[]|select(.key|startswith("/"))|.value.xxxx|select(length == 0)' sample.json
# 配列の中身がないもののkeyを出す
jq 'to_entries[]|select(.key|startswith("/"))|if (.value.xxxx|select(length==0)) then .key else empty end

if 条件 then A else B end の注意点は、上記だと () が必要だった。else 節が必要だった。

ダブルクオートなしでCSV出力したい

単に csv で出力したいなら |@CSV でできるが、ダブルクォーテーションが余計。-r を指定しても残る。ダブルクォーテーションなしで出力するには文字列結合で実現する。デリミタの文字列を変えれば Markdown の表の中間出力にも利用できる。

以下のデータを入力する場合

{
  "key1": [
      {
         "key2": "value2",
         "key3": {
             "key4": "value4"
         },
         "key5": "value5"
      },
      ...
  ]
}

以下のコマンドで、カンマ区切りの一覧を取得できる。

jq -r '.key1[] | [.key2, .key3.key4, .key5] | join(",")' input.json

出力

value2,value4,value5
2
2
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
2
2