I have the following JSON snippet:
{
"a": [ 1, "a:111" ],
"b": [ 2, "a:111", "irrelevant" ],
"c": [ 1, "a:222" ],
"d": [ 1, "b:222" ],
"e": [ 2, "b:222", "irrelevant"]
}
and I would like to swap the key with the second value of the array and accumulate keys with the same value, discarding possible values that come after the second one:
{ "a:111": [ [ 1, "a" ], [ 2, "b" ] ],
"a:222": [ [ 1, "c" ] ],
"b:222": [ [ 1, "d" ], [ 2, "e" ] ]
}
My initial solution is the following:
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]))'
This produces the needed result but is probably not very robust, hard to read and excessively long. I guess there is a much more readable solution using with_entries but it has eluded me for now.