Created
March 2, 2021 07:40
-
-
Save hparadiz/c0c517273618a1c8acbd0c61efc22598 to your computer and use it in GitHub Desktop.
JavaScript <-> PHP compatible JSON canonicalizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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