Files and data
Serialize a flat object with sorted keys
For a flat object with ordinary textual keys, sort the keys before creating a serialized view. This can make small configuration diffs easier to read without changing the original object.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const input = {zebra: 1, apple: 2, mango: 3};
const ordered = Object.fromEntries(Object.keys(input).sort().map(key => [key, input[key]]));
console.log(JSON.stringify(ordered));How it works
The sorted list determines insertion order for these non-integer keys. Rebuilding a separate object leaves the original untouched. This is a presentation technique for simple reports, not a complete specification for canonical JSON across all possible values.
Limits and mistakes
Integer-like property keys have special enumeration ordering, and nested objects remain unsorted. Cryptographic signing requires a real canonicalization scheme with clear rules for numbers, strings, and nesting. Do not reuse this convenience helper as that scheme.
Check the result
Expect {"apple":2,"mango":3,"zebra":1}. Add a nested object and numeric-looking keys to see the boundaries before using sorted output in a broader workflow.
Sources
Reference documentation for the behavior used in this guide: