How can I change a flat key-value pair (with concatenated key) to a nested group. I want to split a key at the ___
and use the new sub-key as key of the nested object.
I have tried map
and split("___")
and the operator |=
but was not able to get it, with jq
Source (Input) file, with flat key-value pair
{
"key1___subkey1-2-foo": "Value 1a",
"key1___subkey1-2-bar": "Value 1b",
"key2___subkey2-2___subkey2-3": "Value 2, Level 3",
"key3": "Value 3"
}
Target format, as nested object
{
"key1": {
"subkey1-2-foo": "Value 1a",
"subkey1-2-bar": "Value 1b"
},
"key2": {
"subkey2-2": {
"subkey2-3": "Value 2, Level 3"
}
},
"key3": "Value 3"
}
CodePudding user response:
jq 'to_entries | map(.key |= split("___")) | reduce .[] as $obj({}; setpath($obj.key; $obj.value))'
The reduce
builds up the object by applying setpath
with input element's key/value in turn