【问题标题】:How do I use jq to flatten a complex json structure?如何使用 jq 展平复杂的 json 结构?
【发布时间】:2021-06-25 19:10:05
【问题描述】:

我有以下简化的 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}'

【问题讨论】:

    标签: json jq flatten recursive-datastructures


    【解决方案1】:

    ..是你的朋友:

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

    【讨论】:

      【解决方案2】:

      如果您的实际输入如此简单,那么从 value 下的每个对象递归提取 idtext 应该可以。

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

      Online demo

      【讨论】:

        【解决方案3】:

        我完全走错了方向

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-29
          相关资源
          最近更新 更多