jq按属性分组 [英] jq group by property in array

查看:344
本文介绍了jq按属性分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入的json文档:

I have an input json document as so:

[
  {
    "Name": "one",
    "Tags": [
      {
        "Key": "Name",
        "Value": "important"
      },
      {
        "Key": "OtherTag",
        "Value": "irrelevant"
      }
    ]
  },
  {
    "Name": "two",
    "Tags": [
      {
        "Key": "OtherTag",
        "Value": "irrelevant2"
      },
      {
        "Key": "Name",
        "Value": "important"
      }
    ]
  },
  {
    "Name": "three",
    "Tags": [
      {
        "Key": "Name",
        "Value": "important2"
      },
      {
        "Key": "OtherTag",
        "Value": "irrelevant3"
      }
    ]
  }
]

我想使用jq将三个记录按值Value分组,其中键=名称".结果将是两个数组,一个数组中有两个记录,一个数组中有一个.具有两个记录的数组将具有两个,因为两个记录共享同一个标记,其值为重要".结果如下所示:

I want to use jq to group the three records by tag Value where the Key = "Name". The result would be two arrays, one with two records in it and one with one. The array with two records would have two because both records share the same tag with a value of "important". Here is what the result would look like:

[
  [
    {
      "Name": "one",
      "Tags": [
        {
          "Key": "Name",
          "Value": "important"
        },
        {
          "Key": "OtherTag",
          "Value": "irrelevant"
        }
      ]
    },
    {
      "Name": "two",
      "Tags": [
        {
          "Key": "OtherTag",
          "Value": "irrelevant2"
        },
        {
          "Key": "Name",
          "Value": "important"
        }
      ]
    },
  ],
  [
    {
      "Name": "three",
      "Tags": [
        {
          "Key": "Name",
          "Value": "important2"
        },
        {
          "Key": "OtherTag",
          "Value": "irrelevant3"
        }
      ]
    }
  ]
]

我只是不知道如何使用jq来做到这一点.有人有什么想法吗?

I just can't figure out how to do this with jq. Does anyone have any ideas?

推荐答案

您提出的解决方案很好,但是如果您不介意将键-值对的数组转换为对象,则可以使用以下方法:

Your proposed solution is fine, but if you don't mind converting the arrays of Key-Value pairs into objects, then the following can be used:

map( .Tags |= from_entries ) | group_by(.Tags.Name) 

这至少使"group_by"易于理解;此外,将.Tags对象转换回键值对(使用小写的键"和值")将很容易:

This at least makes the "group_by" easy to understand; furthermore, it would be easy to convert the .Tags objects back to key-value pairs (with lower-case "key" and "value"):

map( .Tags |= from_entries ) | group_by(.Tags.Name)
| map(map( .Tags |= to_entries))

键/值大小写

恢复大写键/值标签的一种方法是对上述内容进行如下调整:

Key/Value capitalization

One way to recover the capitalized Key/Value tags would be to tweak the above as follows:

def KV: map( {Key: .key, Value: .value} );

map( .Tags |= from_entries ) | group_by(.Tags.Name)
| map(map( .Tags |= (to_entries | KV)))

这篇关于jq按属性分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆