如何使用"类别转换平面对象数组"和"子类别"与JQ树?

时间:2015-06-01 04:17:08

标签: json categories data-manipulation jq

我有一个包含组和子组的JSON对象数组,如下所示:

[
  {
    "Group name": "Elevation", 
    "Subgroup": "Contours", 
    "name": "Contours - Labels"
  }, 
  {
    "Group name": "Elevation", 
    "Subgroup": "Contours", 
    "name": "Contours"
  }, 
  {
    "Group name": "Elevation", 
    "Subgroup": "Cuttings", 
    "name": "Cuttings"
  },
  {
    "Group name": "Framework", 
    "Subgroup": "Reserves", 
    "name": "Reserves"
  }, 
  {
    "Group name": "Framework", 
    "Subgroup": "Indigenous Reserves", 
    "name": "Reserves"
  }, 
  {
    "Group name": "Framework", 
    "Subgroup": "Land Borders", 
    "name": "Mainland"
  }
]

我想将其转换为嵌套结构:

[ { type: group, name: Elevation, Items: [ ... ] } ]

你在JQ怎么做?

2 个答案:

答案 0 :(得分:2)

我不确定您的预期输出是什么,但这可以更有效地完成。通过参数化分组功能,您可以以可重复使用的方式构建树。

def regroup(keyfilter; itemfilter):
    group_by(keyfilter) | map({
        type: "group",
        name: (.[0] | keyfilter),
        items: itemfilter
    })
    ;
regroup(."Group name";
    regroup(.Subgroup;
        map({ name })
    )
)

这会产生以下结果:

[
  {
    "type": "group",
    "name": "Elevation",
    "items": [
      {
        "type": "group",
        "name": "Contours",
        "items": [
          { "name": "Contours - Labels" },
          { "name": "Contours" }
        ]
      },
      {
        "type": "group",
        "name": "Cuttings",
        "items": [
          { "name": "Cuttings" }
        ]
      }
    ]
  },
  {
    "type": "group",
    "name": "Framework",
    "items": [
      {
        "type": "group",
        "name": "Indigenous Reserves",
        "items": [
          { "name": "Reserves" }
        ]
      },
      {
        "type": "group",
        "name": "Land Borders",
        "items": [
          { "name": "Mainland" }
        ]
      },
      {
        "type": "group",
        "name": "Reserves",
        "items": [
          { "name": "Reserves" }
        ]
      }
    ]
  }
]

功能非常强大,您应该尝试更多地使用它。希望这表明它有多么强大。

答案 1 :(得分:0)

这完成了这项工作:

def subgroups:
group_by(."Subgroup")|
map({
  "type": "group", 
  "name": .[0]."Subgroup", 
  "items": (map(del(.Subgroup)))
});

group_by(."Group name")|
map({
  "type": "group", 
  "name": .[0]."Group name", 
  "items": (subgroups2|map(del(."Group name")))
})

它只是同一个过程两次:

  1. group_by对"组名"
  2. 上的外部项目进行排序
  3. 对于每个组,构造一个对象,其名称取自第一个项目,其项目为......
  4. 传递给重复1和2的函数,并删除分组字段。