jq group by属性数组

时间:2015-10-01 21:52:26

标签: json bash shell jq

我有一个输入json文档:

[
  {
    "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按标签值对三条记录进行分组,其中Key =“Name”。结果将是两个数组,一个有两个记录,一个有一个。具有两个记录的数组将具有两个,因为两个记录共享具有值“important”的相同标记。结果如下:

[
  [
    {
      "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执行此操作。有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

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

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

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

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

键/值大写

恢复大写键/值标签的一种方法是按以下方式调整上述内容:

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

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