0
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?

jqコマンドの高度な使い方

Posted at

jqコマンドとは

キーを取得する

a.json
{
  "key1": {
    "Sub-Key11": "Value11",
    "Sub-Key12": "Value12"
  },
  "key2": {
    "Sub-Key21": "Value21",
    "Sub-Key22": "Value22"
  }
}
% jq -r 'keys[]' a.json 
key1
key2

キーを追加する

% jq '. |= .+{"key": {"Sub-Key13": "Value31", "Sub-Key23": "Value32"}}' a.json 
{
  "key1": {
    "Sub-Key11": "Value11",
    "Sub-Key12": "Value12"
  },
  "key2": {
    "Sub-Key21": "Value21",
    "Sub-Key22": "Value22"
  },
  "key": {
    "Sub-Key13": "Value31",
    "Sub-Key23": "Value32"
  }
}

Keyをkey, Valueをvalueとして抽出する

% jq -r 'to_entries[]| .' ~/.a.json
{
  "key": "key1",
  "value": {
    "Sub-Key11": "Value11",
    "Sub-Key12": "Value12"
  }
}
{
  "key": "key2",
  "value": {
    "Sub-Key21": "Value21",
    "Sub-Key22": "Value22"
  }
}

CSVにする

[
  {
    "Key": "key1",
    "Value": "value1"
  },
  {
    "Key": "key2",
    "Value": "value2"
  }
]
jq -r '.[] | [.Key, .Value] | @tsv' b.jaon 
key1    value1
key2    value2

% jq '.[]' a.json 
{
  "Sub-Key11": "Value11",
  "Sub-Key12": "Value12"
}
{
  "Sub-Key21": "Value21",
  "Sub-Key22": "Value22"
}

キーと子要素を同じ階層にする

as で特定の変数を記録する

キーを配列にして、変数にキーをセットしてみると予想通りにハッシュ配列が取れる

% jq '. as $e | keys[] | $e[.]' a.json 
{
  "Sub-Key11": "Value11",
  "Sub-Key12": "Value12"
}
{
  "Sub-Key21": "Value21",
  "Sub-Key22": "Value22"
}

そこにキーを加算すると

% jq '. as $top | keys[] | {"Key": .} + $top[.]' a.json 
{
  "Key": "key1",
  "Sub-Key11": "Value11",
  "Sub-Key12": "Value12"
}
{
  "Key": "key2",
  "Sub-Key21": "Value21",
  "Sub-Key22": "Value22"
}
0
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
0
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?