首页 > 解决方案 > jq:将数据合并到树中

问题描述

我的数据包含categories包含elements. 以 .csv 格式表示,有关类别的数据与每个元素重复。我想通过以 .json 树格式存储数据来避免这种情况。

我该如何整合这一系列elements......</p>

[
  {
    "category": "a",
    "comment": "the repetition, oh my",
    "element_foo": 1,
    "element_bar": 10
  },
  {
    "category": "a",
    "comment": "the repetition, oh my",
    "element_foo": 2,
    "element_bar": 20
  }
],

…进入这个categories包含elements?的数组的数组

[
  {
    "category": "a",
    "comment": "the repetition, oh my",
    "elements": [
      {
        "foo": 1,
        "bar": 10
      },
      {
        "foo": 2,
        "bar": 20
      }
    ]
  }
]

我希望这是一件相当微不足道的jq事情——否则我会写一些更重量级的东西。

标签: jsonjq

解决方案


按类别和评论对对象进行分组,然后根据需要映射分组:

group_by({ category, comment }) | map({
    category: .[0].category,
    comment: .[0].comment,
    elements: map({
        foo: .element_foo,
        bar: .element_bar
    })
})

推荐阅读