Last active
April 7, 2016 01:23
-
-
Save UniDyne/8efb6739f36aed8b015b4e38d343870a to your computer and use it in GitHub Desktop.
Create a canonical JSON string - ideal for cyptographic signing and verifying.
This file contains 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
function getCanonicalJSON(obj) { | |
if(typeof obj === 'object') { | |
var keys = []; | |
// get keys and sort them | |
for(var k in obj) keys.push(k); | |
keys.sort(); | |
// append each kvp to string | |
return '{' + keys.reduce(function(prev, cur, i) { | |
return prev + (i>0?',':'') + '"' + cur + '":' + getCanonicalJSON(obj[cur]); | |
}, '') + '}'; | |
} else if(typeof obj === 'function') { | |
return 'null'; | |
} else return JSON.stringify(obj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment