canonical-json
canonical-json copied to clipboard
Add a comparator for object keys
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"}
ECMAScript 2015 and forward maintains an internal "creation" order which is a very nice feature although hard-core JSON folks think it is lunacy 😂
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.