LoginSignup
2
3

More than 5 years have passed since last update.

jqコマンドで特定のキーだけ抽出する

Posted at

tl;dr

ネストの深いJSONファイルも
jqで階層を指定してすれば
こわくない

背景

以下のような、だるいJSONからupdateKeyvalueを取り出したい

{
  "app": 1,
  "records": [
    {
      "updateKey": {
        "field": "setupdatekey",
        "value": "1"
      },
      "record": {
        "fieldName1": {
          "value": [
            {
              "id": "hoge",
              "value": {
                "fieldName2": {
                  "value": "foo"
                },
              }
            }
          ]
        }
      }
    },
    {
      "updateKey": {
        "field": "setupdatekey",
        "value": "2"
      },
      "record": {
        "fieldName1": {
          "value": [
            {
              "id": "fuga",
              "value": {
                "fieldName2": {
                  "value": "bar"
                },
              }
            }
          ]
        }
      }
    }
  ]
}

具体的には下記のような結果にして、ファイルに書き出したい。

"1"
"2"

方法

jqコマンドで階層を指定して出力すればよい。
上記の例の場合こんな感じ
jq .records[].updateKey.value

所感

JavaScriptとかでJSONを扱うときのように階層を指定することが、
jqでもできることが知らなかった。
ここから発展してワンライナーで色々とできそうだ。
ネストが深いJSONがきても、少しこわくなくなった。

2
3
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
3