简体   繁体   English

如何将值分组到 jq 中相同字段值的数组?

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

I have json data that looks like我有 json 数据看起来像

[
  {
    "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 .我已经设法过滤掉session的唯一值,但可以有更多sessions链接到同一个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现在我想以一种方式合并数据集,以便我在一个地方将session ID 分组到src_ip ,例如

[
...
  {
    "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?这有点类似于此处提出的问题: 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. ,但是我很难将其转换为我的场景。

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.使用group_by ,您可以按任何给定的标准进行分组,然后通过从其中任何一个(例如第一个)中获取它们的公共.src_ip来组装所有分组的项目,并将 .sessions 作为来自所有这些.session.sessions上的映射数组。 Add other parts as you see fit.添加您认为合适的其他部分。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在jq中的多个对象中收集数组值字段的唯一元素? - How do I collect unique elements of an array-valued field across multiple objects in jq? 给定一个json数组,如何使用jq按键提取键值列表? - Given a json array, how do I extract a list of key values by key, using jq? 如何使用数组中的相同值对 HTML 表进行分组(Javascript) - How do I group HTML table with the same value from array (Javascript) 如何多次按字段值对对象数组进行分组? - How can I group an array of objects by field values multiple times? 我怎样才能使数组中的字段值与数组索引相同 - how can i make a field value in an array the same as the array index 在 Ruby 中,如何返回数组中具有相同字符串值的元素的所有索引值? - In Ruby, how do I return all the index value of elements in an array that have the same string values in them? 如何使用jq对可能缺少的数组进行排序? - How do I sort a possibly-absent array with jq? 如何根据特定类别对数组值进行分组 - How do I group array values according to specific category 按字段值对数组进行分组,然后将数组中的分组值推入 - Group an Array by a field value and push grouped values in an array 如何在同一类中将数组的长度设置为字段值? - How can I set length of array to field value in the same class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM