Flatted is a super light (0.5K) and high-performance circular JSON parser that enables serialization and deserialization of JavaScript objects containing circular references. It provides a complete JSON-compatible API while maintaining superior performance and minimal footprint across all modern JavaScript environments.
npm install flattedimport { parse, stringify, toJSON, fromJSON } from "flatted";For CommonJS:
const { parse, stringify, toJSON, fromJSON } = require("flatted");For browser usage (UMD):
<script src="https://unpkg.com/flatted"></script>
<script>
const { parse, stringify, toJSON, fromJSON } = Flatted;
</script>import { parse, stringify, toJSON, fromJSON } from "flatted";
// Create objects with circular references
const a = [{}];
a[0].a = a;
a.push(a);
// Serialize to flatted string
const flattedString = stringify(a);
console.log(flattedString); // [["1","0"],{"a":"0"}]
// Parse back to original structure
const restored = parse(flattedString);
console.log(restored[0].a === restored); // true (circular reference preserved)
// Convert to/from JSON-serializable format
const jsonSafe = toJSON(a); // Convert to JSON-safe format
const original = fromJSON(jsonSafe); // Restore from JSON-safe formatFlatted uses a specialized string encoding that replaces circular references with index references, enabling JSON serialization while preserving object structure. The library provides:
Convert JavaScript values with circular references into specialized flatted strings.
/**
* Converts a JS value into a specialized flatted string
* @param value - The JavaScript value to serialize
* @param replacer - Optional replacer function or array of keys to include
* @param space - Optional spacing for pretty printing
* @returns Flatted string representation
*/
function stringify(
value: any,
replacer?: ((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined,
space?: string | number | undefined
): string;Usage Examples:
import { stringify } from "flatted";
// Basic circular reference
const obj = { name: "test" };
obj.self = obj;
const result = stringify(obj);
// Result: [{"name":"test","self":"0"}]
// With replacer function
const filtered = stringify(obj, (key, value) => {
return key === "self" ? undefined : value;
});
// With replacer array (include only specific keys)
const limited = stringify(obj, ["name"]);
// With pretty printing
const pretty = stringify(obj, null, 2);Convert specialized flatted strings back into JavaScript values with circular references restored.
/**
* Converts a specialized flatted string into a JS value
* @param text - The flatted string to parse
* @param reviver - Optional reviver function to transform values
* @returns Deserialized JavaScript value with circular references restored
*/
function parse(
text: string,
reviver?: (this: any, key: string, value: any) => any
): any;Usage Examples:
import { parse } from "flatted";
// Basic parsing
const flattedString = '[{"name":"test","self":"0"}]';
const obj = parse(flattedString);
console.log(obj.self === obj); // true
// With reviver function
const transformed = parse(flattedString, (key, value) => {
return key === "name" ? value.toUpperCase() : value;
});
console.log(transformed.name); // "TEST"Convert values with circular references into JSON-serializable objects.
/**
* Converts a generic value into a JSON serializable object without losing recursion
* @param value - The value to convert to JSON-serializable format
* @returns JSON-serializable representation preserving circular references
*/
function toJSON(value: any): any;Usage Examples:
import { toJSON } from "flatted";
const circular = { a: 1 };
circular.self = circular;
// Convert to JSON-safe format
const jsonSafe = toJSON(circular);
console.log(JSON.stringify(jsonSafe)); // Can be safely stringified
// Use in APIs or storage
const response = {
data: toJSON(complexObjectWithCircularRefs),
timestamp: Date.now()
};Restore values from JSON-serializable objects back to their original form with circular references.
/**
* Converts a previously serialized object with recursion into a recursive one
* @param value - The JSON-serialized value to restore
* @returns Restored JavaScript value with circular references
*/
function fromJSON(value: any): any;Usage Examples:
import { fromJSON, toJSON } from "flatted";
const original = { name: "test" };
original.self = original;
// Round trip through JSON-safe format
const jsonSafe = toJSON(original);
const stored = JSON.stringify(jsonSafe);
const loaded = JSON.parse(stored);
const restored = fromJSON(loaded);
console.log(restored.self === restored); // true (circular reference preserved)Flatted functions handle errors similar to native JSON methods:
import { parse, stringify } from "flatted";
try {
const result = stringify(undefined); // Throws TypeError
} catch (error) {
console.error("Serialization failed:", error.message);
}
try {
const result = parse("invalid flatted string"); // Throws SyntaxError
} catch (error) {
console.error("Parsing failed:", error.message);
}Flatted provides multiple build formats for different use cases:
import from "flatted" (default for bundlers)require("flatted") (Node.js default)<script> tag creates global Flatted object