Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
...
  {
    "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 :

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)})'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading