Skip to content

Instantly share code, notes, and snippets.

@hparadiz
Created March 2, 2021 07:40
Show Gist options
  • Save hparadiz/c0c517273618a1c8acbd0c61efc22598 to your computer and use it in GitHub Desktop.
Save hparadiz/c0c517273618a1c8acbd0c61efc22598 to your computer and use it in GitHub Desktop.
JavaScript <-> PHP compatible JSON canonicalizer
var canonicalize = function(input) {
if (input === null || typeof input !== 'object') {
/////////////////////////////////////////////////
// Primitive data type - Use ES6/JSON //
/////////////////////////////////////////////////
return JSON.stringify(input);
} else if (Array.isArray(input)) {
/////////////////////////////////////////////////
// Array - Maintain element order //
/////////////////////////////////////////////////
return `[${input.map(element => canonicalize(element)).join(",")}]`;
} else {
/////////////////////////////////////////////////
// Object - Sort keys before serializing //
/////////////////////////////////////////////////
return `{${
Object.keys(input).filter(key => input[key] !== undefined).sort(function(a, b) {
a = Number.isInteger(a)?parseInt(a):a;
b = Number.isInteger(b)?parseInt(b):b;
return a - b;
}).map(key => {
///////////////////////////////////////////////
// Keys are strings - Use ES6/JSON //
///////////////////////////////////////////////
return JSON.stringify(key) + ':'
//////////////////////////////////////////
// value - Recursive expansion //
//////////////////////////////////////////
+ canonicalize(input[key]);
}).join(",")
}}`;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment