Search code examples
jsonjqflattenrecursive-datastructures

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


I have the following simplified json structure: Notice an array of values, which have children, whose children could have children.

{
  "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": ""
            }
          ]
        }
      ]
    }
  ]
}

How do I flatten a json structure using jq? I would like to print each element just once, but in a flat structure. An example output:

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

My attempt doesn't seem to work at all:

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

Solution

  • .. is your friend:

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