Skip to main content

Function Signature

function encode(input: unknown, options?: EncodeOptions): string
Encodes a JavaScript value into TOON format string.

Parameters

input
unknown
required
Any JavaScript value to encode (objects, arrays, primitives). The value will be normalized to JSON-compatible types.
options
EncodeOptions
Optional encoding configuration.
indent
number
default:"2"
Number of spaces per indentation level.
delimiter
Delimiter
default:"DELIMITERS.comma"
Delimiter to use for tabular array rows and inline primitive arrays.
keyFolding
'off' | 'safe'
default:"'off'"
Enable key folding to collapse single-key wrapper chains. When set to 'safe', nested objects with single keys are collapsed into dotted paths (e.g., data.metadata.items instead of nested indentation).
flattenDepth
number
default:"Infinity"
Maximum number of segments to fold when keyFolding is enabled. Controls how deep the folding can go in single-key chains. Values 0 or 1 have no practical effect (treated as effectively disabled).
replacer
EncodeReplacer
A function to transform or filter values during encoding. Called for the root value and every nested property/element. Return undefined to omit properties/elements (root cannot be omitted).
type EncodeReplacer = (
  key: string,
  value: JsonValue,
  path: readonly (string | number)[]
) => unknown

Returns

result
string
TOON formatted string representing the input value.

Examples

import { encode } from 'toon';

const result = encode({ name: 'Alice', age: 30 });
console.log(result);
// Output:
// name: Alice
// age: 30
  • encodeLines - Stream encoding line-by-line for large outputs
  • decode - Decode TOON format back to JavaScript values

Build docs developers (and LLMs) love