Skip to content

Instantly share code, notes, and snippets.

@UniDyne
Last active April 7, 2016 01:23
Show Gist options
  • Save UniDyne/8efb6739f36aed8b015b4e38d343870a to your computer and use it in GitHub Desktop.
Save UniDyne/8efb6739f36aed8b015b4e38d343870a to your computer and use it in GitHub Desktop.
Create a canonical JSON string - ideal for cyptographic signing and verifying.
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