canonical-json icon indicating copy to clipboard operation
canonical-json copied to clipboard

Add a comparator for object keys

Open yeldarby opened this issue 11 years ago • 2 comments

I wanted to be able to specify a custom comparator to sort the keys in an object.

We had to do some programmatic transformations to a large json file and we're using canonical-json to output the result. Our original json is human-consumable so the order of our keys matters but we don't want it to necessarily be alphabetical.

For example:

var obj = {
    first: "a'"
    second: "b",
    third: "c",
    fourth: "d",
    last: "foo"
};

console.log(stringify(obj));

By default, this orders the keys alphabetically and outputs the somewhat disingenuous:

{"first":"a","fourth":"d","last":"foo","second":"b","third":"c"}

If we want to make sure that was output in the expected order, we can use the comparator added in this pull request like so:

console.log(stringify(obj, undefined, undefined, function(a, b) {
    var order = {
        first: 1,
        second: 2,
        third: 3,
        fourth: 4
    };

    return (order[a] || 9999) - (order[b] || 9999);
}));

This outputs the more logically ordered:

{"first":"a","second":"b","third":"c","fourth":"d","last":"foo"}

yeldarby avatar Jul 18 '14 18:07 yeldarby

ECMAScript 2015 and forward maintains an internal "creation" order which is a very nice feature although hard-core JSON folks think it is lunacy 😂

cyberphone avatar Mar 14 '18 12:03 cyberphone

This only provides the feature for 1 of the 2 implementations this repository has. I am not the maintainer, but as a user I would be surprised to find that the two implementations had different features & capabilities.

rektide avatar Mar 21 '20 18:03 rektide