Search code examples
jsonata

How to flatten nested object to single depth object with JSONata?


I am new to JSONata and am having some trouble to create a flatten function.

I want to turn this input:

{
        "user": {
        "key_value_map": {
            "CreatedDate": "123424",
            "Department": {
                "Name": "XYZ"
            }
        }
    }
}

Into this:

{
    "user.key_value_map.CreatedDate": "123424",
    "user.key_value_map.Department.Name": "XYZ"
}

Can anyone help me? Searched here and on google and couldn't find something that would lead me in the right direction.

Thanks


Solution

  • (
        $fn := function($o, $prefix) { 
            $each($o, function($v, $k) {(
                $name := $join([$prefix,$k], '.');
                $type($v) = 'object' ? $fn($v, $name): {
                    $name: $v
                }
            )}) ~> $merge()
        };
        $fn($)
    )
    

    https://try.jsonata.org/WCUxC-r4_