Reputation: 485
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?
Upvotes: 1
Views: 534
Reputation: 26592
This gives exactly the output stated (without "Button" in "Computer" section)
jq '
def get_values:
if has("children") then (.children[]? | get_values) else .name end;
map({name,value:[.children[]? | get_values]}) | from_entries
' input.json
Upvotes: 0
Reputation: 116750
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.
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"
]
}
Upvotes: 1