Deterministic JSON stringification library that ensures consistent output for JavaScript objects regardless of property order
npx @tessl/cli install tessl/npm-fast-json-stable-stringify@2.1.0Fast JSON Stable Stringify provides deterministic JSON stringification that ensures consistent output for JavaScript objects regardless of property order. It offers a faster alternative to existing stable stringify solutions by implementing an optimized algorithm for sorting object keys before serialization.
npm install fast-json-stable-stringifyconst stringify = require('fast-json-stable-stringify');For ES modules (using CommonJS interop):
import stringify from 'fast-json-stable-stringify';Note: This package uses CommonJS exports (module.exports). ES module imports work through CommonJS interoperability.
const stringify = require('fast-json-stable-stringify');
const obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
const result = stringify(obj);
console.log(result);
// Output: {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}Converts JavaScript values to deterministic JSON strings with consistent object key ordering.
/**
* Convert JavaScript value to deterministic JSON string
* @param data - The JavaScript value to stringify
* @param opts - Optional options object or comparison function
* @returns Deterministic JSON string representation
* @throws TypeError - When circular references are detected and cycles option is false
*/
function stringify(data, opts);Parameters:
data (any): The JavaScript value to stringify. Can be objects, arrays, primitives, or nested structuresopts (object|function, optional): Configuration options or legacy comparison functionOptions Object:
interface StringifyOptions {
/** Custom comparison function for object key sorting */
cmp?: (a: CompareObject, b: CompareObject) => number;
/** Controls circular reference handling (default: false) */
cycles?: boolean;
}
interface CompareObject {
key: string;
value: any;
}Usage Examples:
Basic stringification with default alphabetical key sorting:
const stringify = require('fast-json-stable-stringify');
const obj = { c: 6, b: [4,5], a: 3 };
const result = stringify(obj);
// Result: {"a":3,"b":[4,5],"c":6}Custom key sorting with comparison function:
const stringify = require('fast-json-stable-stringify');
const obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
const result = stringify(obj, function (a, b) {
return a.key < b.key ? 1 : -1; // Reverse alphabetical order
});
// Result: {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}Using options object with custom comparison and circular reference handling:
const stringify = require('fast-json-stable-stringify');
const obj = { a: 1 };
obj.self = obj; // Create circular reference
const result = stringify(obj, {
cycles: true,
cmp: function(a, b) {
return a.key.localeCompare(b.key);
}
});
// Result: {"a":1,"self":"__cycle__"}The library handles various JavaScript value types with specific behaviors:
null: Preserved as "null"undefined: Omitted from objects, becomes null in arraysboolean: Preserved as "true" or "false"string: JSON-escaped and quotednumber: Finite numbers as strings, NaN and Infinity become "null"null in arraystoJSON() method: Automatically called before stringificationDetects and handles circular object references with configurable behavior:
const stringify = require('fast-json-stable-stringify');
const obj = { a: 1 };
const child = { parent: obj };
obj.child = child;
// Default behavior - throws TypeError
try {
stringify(obj);
} catch (error) {
console.log(error.message); // "Converting circular structure to JSON"
}
// With cycles enabled - replaces with "__cycle__"
const result = stringify(obj, { cycles: true });
// Result: {"a":1,"child":{"parent":"__cycle__"}}Supports legacy usage where the second parameter is directly a comparison function:
const stringify = require('fast-json-stable-stringify');
const obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 };
const result = stringify(obj, function (a, b) {
return a.value < b.value ? 1 : -1; // Sort by value in reverse order
});Thrown when circular references are detected and the cycles option is false or not specified.
const obj = { a: 1 };
obj.circular = obj;
try {
stringify(obj); // cycles defaults to false
} catch (error) {
console.log(error instanceof TypeError); // true
console.log(error.message); // "Converting circular structure to JSON"
}Note: The actual TypeScript definitions in index.d.ts are incomplete and only define the basic function signature without the opts parameter. The definitions below represent the complete runtime API for reference.
Actual TypeScript Definitions (from index.d.ts):
declare module 'fast-json-stable-stringify' {
function stringify(obj: any): string;
export = stringify;
}Complete Runtime API Types (for reference):
/**
* Main stringification function (CommonJS export)
*/
declare function stringify(data: any, opts?: StringifyOptions | CompareFunction): string;
export = stringify;
/**
* Options for stringification behavior
*/
interface StringifyOptions {
cmp?: CompareFunction;
cycles?: boolean;
}
/**
* Comparison function for custom key sorting
*/
type CompareFunction = (a: CompareObject, b: CompareObject) => number;
/**
* Object structure passed to comparison functions
*/
interface CompareObject {
key: string;
value: any;
}TypeScript Usage Note: Due to the incomplete TypeScript definitions, when using this library in TypeScript projects, you'll need to cast or use type assertions when passing the opts parameter:
import stringify from 'fast-json-stable-stringify';
const obj = { c: 3, a: 1, b: 2 };
// Basic usage (fully typed)
const result1 = stringify(obj);
// With options (requires type assertion)
const result2 = (stringify as any)(obj, { cycles: true });
// Or with custom comparison function
const result3 = (stringify as any)(obj, (a: any, b: any) => a.key.localeCompare(b.key));