Created
August 23, 2024 02:04
-
-
Save miguelmota/4398420c4136b84cb6cf5e681124f193 to your computer and use it in GitHub Desktop.
JavaScript deterministic JSON stringify
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
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