简体   繁体   English

从平面键值对到嵌套对象的 JSON

[英]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我已经尝试过mapsplit("___")以及运算符|=但无法使用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和输入元素的键/值来构建对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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