inferSchema
Infer a SchemaNode tree from any JSON value.
Signature
function inferSchema(value: unknown, options?: InferOptions): SchemaNode;Options
| Option | Type | Default | Description |
|---|---|---|---|
mode | "sampled" | "exhaustive" | "sampled" | sampled picks 3 elements (first, middle, last). exhaustive infers every element. |
maxDepth | number | 10 | Maximum recursion depth. Objects/arrays beyond this depth become opaque {} or count-only. |
Try it: Primitives
The four primitive types: string (with character length), number, boolean, null.
Try it: Array of Objects
All elements have the same keys — no optional marking needed.
Try it: Optional Keys
Some elements have email, others don't — the schema marks it optional: true. The label key only appears on one element but is still discovered.
Try it: Varying Array Sizes
Nested arrays with different lengths across elements get varyingSizes: true instead of a misleading count.
Try it: Mixed Types (Union)
When array elements have different types, the schema produces a union. Switch between sampled and exhaustive to see how sampling can miss elements.
Try it: Union Deduplication
Multiple objects merge into one variant with a variantCount. Here 3 objects become one variant with variantCount: 3.
Try it: Mixed Value Types per Key
When the same key has different types across objects (e.g. value_code is sometimes a string, sometimes a number), the schema produces a union for that key.
Try it: Donor Elements (Sampled Mode)
With 7 elements, sampled picks indices [0, 3, 6]. The label key only exists on element 5 — not sampled. The donor mechanism discovers it by scanning all keys, then finding an element that has it to infer the type.
Try it: Depth Control
Drag the maxDepth slider to see how depth limiting works. At depth 1, nested objects become opaque {}. At depth 2+, keys start appearing.
Try it: Deeply Nested (CMS-style)
Real-world CMS data with 7+ levels of nesting. At the default maxDepth: 10, banner objects are fully expanded.
SchemaNode Structure
interface SchemaNode {
type: "string" | "number" | "boolean" | "null" | "object" | "array" | "union";
length?: number; // string character count
keys?: Record<string, SchemaNode>; // object keys
items?: SchemaNode; // array item schema
count?: number; // array element count
varyingSizes?: boolean; // nested arrays with different lengths
optional?: boolean; // key only in some array elements
variants?: SchemaNode[]; // union type variants
variantCount?: number; // elements matching this variant
}