CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-flatted

A super light and fast circular JSON parser

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Flatted

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.

Package Information

  • Package Name: flatted
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install flatted

Core Imports

import { 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>

Basic Usage

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 format

Architecture

Flatted uses a specialized string encoding that replaces circular references with index references, enabling JSON serialization while preserving object structure. The library provides:

  • Parse/Stringify API: Direct serialization/deserialization like JSON.parse/stringify
  • JSON Bridge API: toJSON/fromJSON for working with JSON-safe intermediate formats
  • Multiple Module Formats: ESM, CommonJS, UMD for maximum compatibility
  • Reviver/Replacer Support: Full compatibility with JSON.parse/stringify parameters

Capabilities

String Serialization

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);

String Parsing

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"

JSON Serialization

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()
};

JSON Deserialization

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)

Error Handling

Flatted functions handle errors similar to native JSON methods:

  • stringify: Throws TypeError for non-serializable values (functions, undefined, symbols)
  • parse: Throws SyntaxError for malformed flatted strings
  • toJSON/fromJSON: Handle the same error cases as their underlying parse/stringify calls
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);
}

Performance Considerations

  • Size: 0.5K compressed, minimal runtime overhead
  • Speed: Optimized for performance, faster than alternatives like CircularJSON
  • Memory: Efficient circular reference tracking with minimal memory usage
  • Compatibility: Works in all modern JavaScript environments (Node.js, browsers, workers)

Module Formats

Flatted provides multiple build formats for different use cases:

  • ESM: import from "flatted" (default for bundlers)
  • CommonJS: require("flatted") (Node.js default)
  • UMD: Browser <script> tag creates global Flatted object
  • Minified: Production-ready compressed versions available
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/flatted@3.3.x
Publish Source
CLI
Badge
tessl/npm-flatted badge