jq find all nested children names and flatten json depth

I’ve a json looking like

[
  {
    "name": "Architektur"
  },
  {
    "name": "Computer",
    "children": [
      {
        "name": "Icon"
      },
      {
        "name": "Pattern"
      },
      {
        "name": "Button",
        "children": [
          {
            "name": "grün"
          },
          {
            "name": "braun"
          }
        ]
      }
    ]
  },
  {
    "name": "Fahrzeug"
  },
  {
    "name": "Kamera",
    "children": [
      {
        "name": "Histogramm"
      },
      {
        "name": "Weißableich",
        "children": [
          {
            "name": "Auto"
          },
          {
            "name": "Sonne"
          },
          {
            "name": "Bewölkt",
            "children": [
              {
                "name": "Am Tag"
              },
              {
                "name": "In der Nacht"
              }
            ]
          }
        ]
      },
      {
        "name": "Sensor"
      }
    ]
  }
]

I would now need to get the first level name (f.e. Computer) as parent and search for all children names of any depth (f.e. Icon, Pattern). Those child names should be added as array to the first level parent value. If there are no children at all (f.e. Architektur) the array should stay empty. This is what it should look like:

{
 "Architektur": [],
 "Computer": ["Icon", "Pattern", "grün", "braun"],
 "Fahrzeug": [],
 "Kamera": ["Histogramm","Auto", "Sonne", "Am Tag", "In der Nacht"],
 "Sensor": []
}

Unfortunately with jq I could not arrive to somewhere useful, (Missing knowledge), but before diving in python I would like to ask if this is possible?

>Solution :

Here’s a straightforward solution to the problem as stated, courtesy of ..:

def children: objects | select(has("children")) | .children[].name;
map( {(.name) : [..|children]} ) | add

Please note, though, that the output you show as being expected does not seem to correspond exactly to the stated requirements.


Output

Here’s the output produced by the mini-program when run against the sample:

{
  "Architektur": [],
  "Computer": [
    "Icon",
    "Pattern",
    "Button",
    "grün",
    "braun"
  ],
  "Fahrzeug": [],
  "Kamera": [
    "Histogramm",
    "Weißableich",
    "Sensor",
    "Auto",
    "Sonne",
    "Bewölkt",
    "Am Tag",
    "In der Nacht"
  ]
}

Leave a Reply