简体   繁体   中英

JSON from flat key-value pair to nested object

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

jq 'to_entries | map(.key |= split("___")) | reduce .[] as $obj({}; setpath($obj.key; $obj.value))'

reduce通过setpath应用setpath和输入元素的键/值来构建对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM