Use JSONata to alpha sort keys in a JSON object

350 Views Asked by At

I'll start off by saying I'm aware that, acording to json.org, "An object is an unordered set of name/value pairs." Nonetheless, in the real world, sometimes it would be nice to view keys in alphabetical order.

Unsorted:

{"B":2,"A":1,"C":3}

Sorted:

{"A":1,"B":2,"C":3}

Is there a way to do this in JSONata? (I understand I can pre- or post-process the data outside JSONata, but am curious whether there's a way to do this via JSONata.)

Thank you.

1

There are 1 best solutions below

0
On

I have just written the following function:

$sortObjectAlphabetically := function($obj){
    (
        $keys := [$keys($obj)];
        $keys := $keys^(<$);
        $merge([$map($keys,function($e){
            (
                {
                    $e : $lookup($obj,$e)
                }
            )
        })]);
    )
};

I've done an example at this link: https://try.jsonata.org/RbJqQxO0i