Last active
March 6, 2025 02:17
-
-
Save davidfurlong/463a83a33b70a3b6618e97ec9679e490 to your computer and use it in GitHub Desktop.
JSON.stringify replacer function for having object keys sorted in output (supports deeply nested objects)
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
// Spec http://www.ecma-international.org/ecma-262/6.0/#sec-json.stringify | |
const replacer = (key, value) => | |
value instanceof Object && !(value instanceof Array) ? | |
Object.keys(value) | |
.sort() | |
.reduce((sorted, key) => { | |
sorted[key] = value[key]; | |
return sorted | |
}, {}) : | |
value; | |
// Usage | |
// JSON.stringify({c: 1, a: { d: 0, c: 1, e: {a: 0, 1: 4}}}, replacer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bcowgill A nice edge case! What about using this expression
value instanceof Object && !Array.isArray(value) && Object.keys(value).length > 0
to make it more succinct?