An object (UnknownRecord
) to serialize. Must be a plain
object (not an array, primitive, or null). Nested objects and arrays
within the object will also have their keys sorted alphabetically.
Optional
space: string | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10Optional formatting parameter:
A Result<string, string>
containing:
Result.ok(jsonString)
with all object keys sorted
alphabeticallyResult.err(errorMessage)
describing the serialization errorconst unorderedData = {
zebra: 1,
apple: 2,
mango: 3,
nested: {
zulu: 'z',
alpha: 'a',
beta: 'b',
},
};
// Keys will be sorted alphabetically at all levels
const sorted = Json.stringifySortedKey(unorderedData);
assert.ok(Result.isOk(sorted));
if (Result.isOk(sorted)) {
// Keys should appear in alphabetical order
const expected =
'{"apple":2,"mango":3,"nested":{"alpha":"a","beta":"b","zulu":"z"},"zebra":1}';
assert(sorted.value === expected);
}
// With formatting
const formatted = Json.stringifySortedKey(unorderedData, 2);
assert.ok(Result.isOk(formatted));
if (Result.isOk(formatted)) {
// Check that keys are in order (first key should be "apple")
assert.ok(
formatted.value.indexOf('"apple"') < formatted.value.indexOf('"mango"'),
);
assert.ok(
formatted.value.indexOf('"mango"') < formatted.value.indexOf('"nested"'),
);
assert.ok(
formatted.value.indexOf('"nested"') < formatted.value.indexOf('"zebra"'),
);
}
Safely converts a JavaScript record to a JSON string with keys sorted alphabetically at all levels.
This function creates deterministic JSON output by ensuring that object keys appear in alphabetical order at every level of nesting. This is particularly useful for creating consistent output for comparison, hashing, caching, or when you need reproducible JSON representations across different JavaScript engines or runs.