Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created August 23, 2024 02:04
Show Gist options
  • Save miguelmota/4398420c4136b84cb6cf5e681124f193 to your computer and use it in GitHub Desktop.
Save miguelmota/4398420c4136b84cb6cf5e681124f193 to your computer and use it in GitHub Desktop.
JavaScript deterministic JSON stringify
import stringify from 'json-stable-stringify'
// Helper function to recursively sort arrays of objects
function sortNestedArrays(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(sortNestedArrays).sort((a, b) => {
if (typeof a === 'object' && typeof b === 'object') {
return JSON.stringify(a).localeCompare(JSON.stringify(b))
}
return 0
})
} else if (obj !== null && typeof obj === 'object') {
const sortedObj: Record<string, any> = {}
Object.keys(obj).sort().forEach(key => {
sortedObj[key] = sortNestedArrays(obj[key])
})
return sortedObj
}
return obj
}
// Generalized function to stringify objects deterministically
function deterministicStringify(obj: any): string {
const sortedObj = sortNestedArrays(obj)
return stringify(sortedObj)
}
// expect(deterministicStringify(objectA)).toEqual(deterministicStringify(objectB))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment