如何使用 jq 来展平复杂的 json 结构?

How do I use jq to flatten a complex json structure?

我有以下简化的 json 结构:注意值数组,它有子项,其子项可以有子项。

{
  "value": [
    {
      "id": "12",
      "text": "Beverages",
      "state": "closed",
      "attributes": null,
      "iconCls": null
    },
    {
      "id": "10",
      "text": "Foods",
      "state": "closed",
      "attributes": null,
      "iconCls": null,
      "children": [
        {
          "id": "33",
          "text": "Mexican",
          "state": "closed",
          "attributes": null,
          "iconCls": null,
          "children": [
            {
              "id": "6100",
              "text": "Taco",
              "count": "3",
              "attributes": null,
              "iconCls": ""
            }
          ]
        }
      ]
    }
  ]
}

如何使用 jq 展平 json 结构?我想只打印一次每个元素,但采用平面结构。示例输出:

{
  "id": "12",
  "category": "Beverages"
},
{
  "id": "10",
  "category": "Foods"
},
{
  "id": "33",
  "category": "Mexican"
},
{
  "id": "6100",
  "category": "Tacos"
}

我的尝试似乎根本不起作用:

cat simple.json - | jq '.value[] | {id: .id, category: .text} + {id: .children[]?.id, category: .children[]?.text}'

..是你的朋友:

.. | objects | select( .id and .text) | {id, category: .text}

如果您的实际输入就这么简单,从 value[= 下的每个对象递归提取 idtext 20=] 应该有效。

[ .value | recurse | objects | {id, category: .text} ]

Online demo

I was totally going in the wrong direction

不是真的。朝那个方向前进,你会得到类似的东西:

.value[] 
| recurse(.children[]?) 
| {id, category: .text}