jq:按属性分组和键

时间:2021-11-06 07:38:44

I have a list of objects that look like this:

我有一个对象列表,如下所示:

[
  {
    "ip": "1.1.1.1",
    "component": "name1"
  },
  {
    "ip": "1.1.1.2",
    "component": "name1"
  },
  {
    "ip": "1.1.1.3",
    "component": "name2"
  },
  {
    "ip": "1.1.1.4",
    "component": "name2"
  }
]

Now I'd like to group and key that by the component and assign a list of ips to each of the components:

现在,我想对组件进行分组和键入,并为每个组件分配一个ips列表:

{
  "name1": [
    "1.1.1.1",
    "1.1.1.2"
  ]
},{
  "name2": [
    "1.1.1.3",
    "1.1.1.4"
  ]
}

1 个解决方案

#1


10  

I figured it out myself. I first group by .component and then just create new lists of ips that are indexed by the component of the first object of each group:

我自己弄清楚了。我首先按.component分组,然后只创建由每个组的第一个对象的组件索引的新的ips列表:

jq ' group_by(.component)[] | {(.[0].component): [.[] | .ip]}'

jq'group_by(.component)[] | {(。[0] .component):[。[] | .IP]}”

#1


10  

I figured it out myself. I first group by .component and then just create new lists of ips that are indexed by the component of the first object of each group:

我自己弄清楚了。我首先按.component分组,然后只创建由每个组的第一个对象的组件索引的新的ips列表:

jq ' group_by(.component)[] | {(.[0].component): [.[] | .ip]}'

jq'group_by(.component)[] | {(。[0] .component):[。[] | .IP]}”