0

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"
}

2

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks I have not worked with reduce before. Great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.