0

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.

  • Does this answer your question? [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – derpirscher May 23 '21 at 20:15
  • Thanks for asking. No it doesn't. I'm referring specifically to sorting object keys via JSONata. – Kevin Frank May 24 '21 at 01:56
  • Question has been edited to make this clearer. – Kevin Frank May 24 '21 at 02:08

1 Answers1

1

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

cigien
  • 57,834
  • 11
  • 73
  • 112