交换键和值并累积值

时间:2018-06-13 10:26:05

标签: json linux key-value reduce jq

我有以下JSON代码段:

{
  "a": [ 1, "a:111" ],
  "b": [ 2, "a:111", "irrelevant" ],
  "c": [ 1, "a:222" ],
  "d": [ 1, "b:222" ],
  "e": [ 2, "b:222", "irrelevant"]
}

我希望将密钥与数组的第二个值交换,并使用相同的值累积密钥,丢弃第二个之后的可能值:

{ "a:111": [ [ 1, "a" ], [ 2, "b" ] ],
  "a:222": [ [ 1, "c" ] ],
  "b:222": [ [ 1, "d" ], [ 2, "e" ] ]
}

我的初步解决方案如下:

echo  '{
      "a": [ 1, "a:111" ],
      "b": [ 2, "a:111", "irrelevant" ],
      "c": [ 1, "a:222" ],
      "d": [ 1, "b:222" ],
      "e": [ 2, "b:222", "irrelevant"]
    }' \
| jq 'to_entries
| map({(.value[1]|tostring) : [[.value[0], .key]]})
| reduce .[] as $o ({}; reduce ($o|keys)[] as $key (.; .[$key] += $o[$key]))'

这会产生所需的结果,但可能不是非常强大,难以阅读且过长。我想使用 with_entries 有一个更易读的解决方案,但现在它已经没有了。

1 个答案:

答案 0 :(得分:2)

jq 方法:

jq 'reduce to_entries[] as $o ({};
    .[$o.value[1]] += [[$o.value[0], $o.key]])' input.json

输出:

{
  "a:111": [
    [
      1,
      "a"
    ],
    [
      2,
      "b"
    ]
  ],
  "a:222": [
    [
      1,
      "c"
    ]
  ],
  "b:222": [
    [
      1,
      "d"
    ],
    [
      2,
      "e"
    ]
  ]
}