stablify
v1.2.0
Published
Deterministic JSON.stringify with sorted keys. Drop-in replacement for fast-json-stable-stringify (same output), plus space, replacer, BigInt and clear cycle handling. Zero dependencies.
Maintainers
Readme
stablify
JSON.stringify with sorted keys, so the same data always gives the same string.
JSON.stringify writes object keys in the order they were added. So { a: 1, b: 2 } and { b: 2, a: 1 } give two different strings, even though the data is the same. stablify sorts the keys at every level, so equal data always gives the same string. Use it for cache keys, hashes, signatures and snapshot tests. It is a drop-in replacement for fast-json-stable-stringify: same output, but faster.
Features
- Same output as
fast-json-stable-stringify, byte for byte, for all JSON data. The tests check this on thousands of random values. - Faster: 1.16 to 1.74 times the speed of
fast-json-stable-stringifyin our benchmarks (see Performance). - Everything
JSON.stringifyhas:spacefor pretty-printing,replacerfunctions and key allowlists,toJSON. - Clear errors for circular references: a
TypeErrorthat tells you about{ cycles: true }. This includes cycles through arrays, which overflow the stack infast-json-stable-stringify. - BigInt support: throws like
JSON.stringifyby default, or writes BigInts as strings or numbers. - Custom key order with the same
cmp({ key, value }, { key, value })signature asfast-json-stable-stringify. - Zero dependencies, ESM and CommonJS, TypeScript types included. Works in Node.js 20+, Bun, Deno and browsers.
Installation
npm install stablifypnpm add stablify
yarn add stablify
bun add stablifyQuick start
import stablify from 'stablify'
// Key order does not change the result
stablify({ b: 2, a: 1 }) // => '{"a":1,"b":2}'
stablify({ a: 1, b: 2 }) // => '{"a":1,"b":2}'
// Keys are sorted at every level. Arrays keep their order.
stablify({ c: 8, b: [{ z: 6, y: 5, x: 4 }, 7], a: 3 })
// => '{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}'
// Pretty-print, with sorted keys
stablify({ b: 1, a: 2 }, { space: 2 })
// => '{\n "a": 2,\n "b": 1\n}'
// BigInt values as strings
stablify({ id: 12345678901234567890n }, { bigint: 'string' })
// => '{"id":"12345678901234567890"}'With CommonJS, use const stablify = require('stablify'). The function is also a named export: import { stablify } from 'stablify'.
Table of contents
- Usage
- API
- Comparison
- Performance
- Migrating from fast-json-stable-stringify
- Notes and limitations
- Requirements
- License
Usage
Build a cache key from an object
A cache key must be the same every time you ask for the same thing. With JSON.stringify, two equal queries can give two different keys, so you miss the cache. With stablify, they give one key.
const a = { status: 'open', page: 2 }
const b = { page: 2, status: 'open' }
JSON.stringify(a) === JSON.stringify(b) // => false
stablify(a) === stablify(b) // => true
const cache = new Map()
cache.set(stablify(a), ['result'])
cache.get(stablify(b)) // => ['result']Hash or sign data
A hash (a short fingerprint of some data) or a signature (a hash that proves who made the data) is computed from the exact bytes. If the key order changes, the hash changes too, and a valid signature fails to check. Sort the keys first:
import { createHash } from 'node:crypto'
const hash = (data) => createHash('sha256').update(stablify(data)).digest('hex')
hash({ a: 1, b: 2 }) === hash({ b: 2, a: 1 }) // => trueGet clean snapshot diffs
Snapshot tests and files saved to Git show a diff when the text changes. If the key order changes between runs, you see a large diff, but nothing really changed. With sorted keys, the diff shows only the real changes.
import { writeFileSync } from 'node:fs'
writeFileSync('config.json', stablify(config, { space: 2 }) + '\n')Pretty-print the output
space works like the third argument of JSON.stringify: a number of spaces (up to 10) or a string (up to 10 characters).
stablify({ b: [1], a: 1 }, { space: 2 })
// =>
// {
// "a": 1,
// "b": [
// 1
// ]
// }
stablify({ b: 1, a: 2 }, { space: '\t' }) // => '{\n\t"a": 2,\n\t"b": 1\n}'Leave out some values
A replacer function works like the second argument of JSON.stringify. Return undefined to leave a property out.
const user = { name: 'Ada', password: 'secret' }
stablify(user, { replacer: (key, value) => (key === 'password' ? undefined : value) })
// => '{"name":"Ada"}'Keep only some keys
Pass an array of keys as replacer. Only these keys are written, at every level. The output keys are still sorted, not written in the order of your list.
stablify({ id: 1, name: 'Ada', secret: 'x' }, { replacer: ['name', 'id'] })
// => '{"id":1,"name":"Ada"}'Handle circular references
A circular reference is an object that contains itself, directly or through other objects or arrays. By default, stablify throws a TypeError, like JSON.stringify. With cycles: true, it writes "__cycle__" in its place.
const user = { name: 'Ada' }
user.self = user
stablify(user) // throws TypeError
stablify(user, { cycles: true }) // => '{"name":"Ada","self":"__cycle__"}'
const list = []
list.push(list)
stablify(list, { cycles: true }) // => '["__cycle__"]'The same object can appear in several places, as long as it does not contain itself:
const point = { x: 1 }
stablify({ a: point, b: point }) // => '{"a":{"x":1},"b":{"x":1}}'Write BigInt values
JSON.stringify throws on BigInt values. stablify does the same by default, but you can choose another mode:
const data = { id: 12345678901234567890n }
stablify(data) // throws TypeError
stablify(data, { bigint: 'string' }) // => '{"id":"12345678901234567890"}'
stablify(data, { bigint: 'number' }) // => '{"id":12345678901234567890}'With 'number', the result is valid JSON. But JSON.parse rounds numbers above 2^53, so you may not get the same number back.
Use a custom key order
cmp gets two { key, value } objects and returns a number, like a comparator for Array.prototype.sort(). You can also pass the function directly as the second argument, as in fast-json-stable-stringify.
const reverse = (a, b) => (a.key < b.key ? 1 : -1)
stablify({ a: 1, b: 2 }, { cmp: reverse }) // => '{"b":2,"a":1}'
stablify({ a: 1, b: 2 }, reverse) // => '{"b":2,"a":1}'Know how special values are written
Everything except the key order follows JSON.stringify:
stablify({ when: new Date(0) }) // => '{"when":"1970-01-01T00:00:00.000Z"}'
stablify({ a: undefined, f() {}, b: 1 }) // => '{"b":1}'
stablify([undefined, NaN, Infinity]) // => '[null,null,null]'
stablify(new Map([['a', 1]])) // => '{}'
stablify(undefined) // => undefinedtoJSONis used, soDatevalues become ISO strings.undefined, functions and symbols are left out of objects, and becomenullin arrays.NaNandInfinitybecomenull.MapandSethave no own keys, so they become{}. Convert them first if you need their contents, for example withObject.fromEntries(map)or[...set].- When
valueitself isundefined, a function or a symbol, the result isundefined.
API
stablify(value, options?)
function stablify(value: unknown, options?: StablifyOptions | Comparator): stringReturns the JSON string of value, with object keys sorted at every level. Keys are sorted by UTF-16 code unit, the same as Array.prototype.sort() with no comparator. Like JSON.stringify, it returns undefined when value is undefined, a function or a symbol.
The second argument is an options object, or a comparator function (the same as { cmp }). This is the default export and also a named export.
| Option | Type | Default | Description |
|---|---|---|---|
| cmp | Comparator | sort by UTF-16 code unit | Custom key order. Gets { key, value } for both keys and returns a number. Throws a TypeError if it is not a function. |
| cycles | boolean | false | false: circular references throw a TypeError. true: they are written as "__cycle__". |
| space | string \| number | none | Indentation, the same as the third argument of JSON.stringify. Numbers are capped at 10 spaces, strings at 10 characters. |
| replacer | ReplacerFunction \| (string \| number)[] \| null | none | The same as the second argument of JSON.stringify: a function, or a list of the only keys to include. |
| bigint | 'throw' \| 'string' \| 'number' | 'throw' | What to do with BigInt values. Any other value throws a TypeError. |
replacer details. A function is called as replacer.call(holder, key, value) for every value, after toJSON. holder is the object that holds the key. The first call is for the top-level value, with key ''. An array is a list of the only keys to include, at every level.
bigint details.
'throw'(default): throw aTypeError, likeJSON.stringify.'string': write BigInts as JSON strings:"12345678901234567890".'number': write the digits as a JSON number:12345678901234567890. This is valid JSON, butJSON.parserounds numbers above 2^53.
A BigInt.prototype.toJSON or a replacer is used first, as with JSON.stringify.
Types
All types are exported:
import type { StablifyOptions, Comparator, CompareEntry, ReplacerFunction } from 'stablify'StablifyOptions is the options object above. The other types are:
interface CompareEntry { key: string; value: unknown }
type Comparator = (a: CompareEntry, b: CompareEntry) => number
type ReplacerFunction = (this: any, key: string, value: any) => anyComparison
fast-json-stable-stringify works, but it has not had a release since 2019 and does only the basics. stablify gives the same output and adds what was missing:
| | fast-json-stable-stringify | stablify |
|---|---|---|
| Sorted keys, same output | Yes | Yes, identical |
| Custom key order (cmp) | Yes | Yes, same signature |
| cycles: true | Yes | Yes |
| Circular arrays | No (stack overflow) | Yes (TypeError or "__cycle__") |
| Pretty-printing (space) | No | Yes |
| replacer (function or key list) | No | Yes |
| BigInt | No (throws) | Yes (throws by default, or 'string' / 'number') |
| ESM and CommonJS, types included | CommonJS only | Yes |
Performance
Measured with Node 20.14 on an Intel Core i7-1355U. Operations per second, higher is better:
| Input | fast-json-stable-stringify | stablify | Speed-up |
|---|---|---|---|
| Small object (5 keys) | 1,266,882 | 2,101,982 | 1.66x |
| Array of 100 records | 7,264 | 12,617 | 1.74x |
| Random nested data | 144 | 216 | 1.50x |
| One object with 200 keys | 32,536 | 37,760 | 1.16x |
| 100 records with cmp | 5,793 | 7,609 | 1.31x |
| 100 records with cycles: true | 6,902 | 11,951 | 1.73x |
Your numbers will change with your hardware and data. space and replacer use a separate code path that follows the JSON.stringify steps exactly. It is a little slower, and it was not part of these measurements.
Migrating from fast-json-stable-stringify
Before:
const stringify = require('fast-json-stable-stringify')After:
const stringify = require('stablify')Your existing output (cache keys, hashes, snapshots) stays the same. The only differences are for inputs where the old package did something unusual:
- Boxed primitives (
new Number(1),new String('a')) are written as their value, likeJSON.stringifydoes:1and"a".fast-json-stable-stringifywrote them as objects:{}and{"0":"a"}. toJSON(key)gets the property name, like withJSON.stringify. The old package calledtoJSON()with no argument. This matters only if yourtoJSONuses its argument.- Circular arrays throw a
TypeError(or become"__cycle__"withcycles: true). The old package overflowed the stack.
Notes and limitations
- Keys are sorted by UTF-16 code unit, not in "natural" order. So
"10"comes before"2", and"B"comes before"b". Usecmpif you need another order. MapandSetbecome{}, as withJSON.stringify. Convert them to objects or arrays first.bigint: 'number'can lose precision when the JSON is read back withJSON.parse, for numbers above 2^53.- A key allowlist does not set the output order. The listed keys are still written in sorted order.
spaceandreplacerare a little slower than the default mode, because they use a separate code path.
Requirements
- Node.js 20 or newer. Also works in Bun, Deno and browsers.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
