Search code examples
jsonata

Jsonata to convert flat structure to tree or hierarchy


Can someone help me with the jsonata to convert this flat structure:

[
  {
    "Id": 1,
    "ParentId": 0
  },
  {
    "Id": 2,
    "ParentId": 1
  },
  {
    "Id": 3,
    "ParentId": 1
  },
  {
    "Id": 4,
    "ParentId": 1
  },
  {
    "Id": 5,
    "ParentId": 2
  },
  {
    "Id": 6,
    "ParentId": 2
  },
  {
    "Id": 7,
    "ParentId": 2
  },
  {
    "Id": 8,
    "ParentId": 3
  },
  {
    "Id": 9,
    "ParentId": 4
  }
]

To a heirarchy of:

{
    "Id": 0,
    "child" : [
        {
        "Id": 1,
        "child" : [
            {
            "Id":2,
            "child" : [
                {"Id": 5},
                {"Id": 6},
                {"Id": 7}
                ]
            },
            {
            "Id":3,
            "child" : [
                {"Id": 8}
                ]
            },  
            {"Id":4}
            "child" : [
                {"Id": 9}
                ]
            }
        }
    ]
}

I may be off on the exact output, like have some commas missing or syntax but that's the rough idea of the output

Here is a link to jsonata exerciser: https://try.jsonata.org/a6RVSrrYG


Solution

  • (
      $map := function($array, $id) {
        $filter($array, function($v) { $v.ParentId = $id }).{
          "Id": Id,
          "child": $map($array, Id)
        }
      };
      $map($, 0)
    )