'How do I group values to an array for the same field value in jq?

I have json data that looks like

[
  {
    "session": "ffe887f3f150",
    "src_ip": "81.71.87.156"
  },
  {
    "session": "fff42102e329",
    "src_ip": "143.198.224.52"
  },
  {
    "session": "fff9c8ca82be",
    "src_ip": "159.203.97.7"
  }
]

I've managed to filter out unique values of session but there can be more sessions linked to a same src_ip.

Now I would like to merge the dataset in a way so that I have grouped session ID's to src_ip at one place such as

[
...
  {
    "src_ip": "81.71.87.156"
    "sessions": ["ffe887f3f150","fff42102e329"]
  },
...
]

This is somewhat similar to question asked here: How do I collect unique elements of an array-valued field across multiple objects in jq? , however I struggle to transform that for my scenario.



Solution 1:[1]

With group_by you can group by any criteria given, then assemble all grouped items by taking their common .src_ip from any of them (eg. the first), and .sessions as a mapped array on .session from all of them. Add other parts as you see fit.

jq 'group_by(.src_ip) | map({src_ip: .[0].src_ip, sessions: map(.session)})'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1