Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a comparator for object keys #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

yeldarby
Copy link

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"}

@cyberphone
Copy link

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

@rektide
Copy link

rektide commented Mar 21, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants