How to unflatten a JSON object?

Viewed 281

How to convert the flattened JSON like following

{
  "foo.bar1": "1",
  "foo.bar2": "2",
  "foo.bar3.doo1": "3",
  "foo.bar3.doo2" : "4"
}

to be nested like

{
  "foo": {
    "bar1": "1",
    "bar2": "2",
    "bar3": {
      "doo1": "3",
      "doo2": "4"
    }
  }
}

? I could find many posts about flattening a nested JSON, but not vice versa.

1 Answers

Convert keys to paths, and put the values in their original places using setpath.

. as $in | reduce keys_unsorted[] as $k ({}; setpath($k / "."; $in[$k]))

Online demo

Related