Deterministic JSON Schema Inference & Multi-Language Type Generation in the Browser
Pasting production API responses into third-party code-generation websites exposes bearer tokens, customer records, and internal payload structures to external servers. At the same time, naive JSON-to-TypeScript converters fail as soon as an array contains heterogeneous elements: a field present in item 0 might be omitted in item 1, or hold null in item 2, or change from an integer (49) to a floating-point number (29.99).
For the client-side Sunasty JSON to TypeScript / Zod / Go / Rust / Pydantic Generator, we designed a pure TypeScript two-stage compiler that builds a structural AST first (InferredSchema) and renders idiomatic source code for six targets inside browser memory without sending JSON payloads over the network.
1. Structural Schema Lattice & Heterogeneous Array Merging
Every parsed JSON node is first lifted into a tagged union (null, boolean, integer, number, string, any, array, or object). Tracking integer separately from floating-point number allows generators targeting Go (int vs float64), Rust (i64 vs f64), Pydantic (int vs float), and JSON Schema Draft 2020-12 to emit tight numeric types when all observed values are integers, while widening cleanly when mixed.
export function mergeSchemas(a, b) {
if (a.kind === b.kind) {
if (a.kind === 'array') {
return { kind: 'array', element: mergeSchemas(a.element, b.element) };
}
if (a.kind === 'object') {
return { kind: 'object', fields: mergeObjectSchemas(a.fields, b.fields) };
}
return a;
}
// Integer + Float coerces to float64 / number rather than unknown
if ((a.kind === 'integer' && b.kind === 'number') ||
(a.kind === 'number' && b.kind === 'integer')) {
return { kind: 'number' };
}
// Merging with null preserves the concrete sibling schema
if (a.kind === 'null') return b;
if (b.kind === 'null') return a;
return { kind: 'any' };
}
2. Separating Optional (?) from Nullable (| null)
A common defect in quick schema generators is conflating missing keys with explicit null values. During mergeObjectSchemas(aFields, bFields), each key across the union of both objects is tracked independently:
- Key absent in one element: marks
optional: trueon the mergedInferredFieldwhile keeping the concrete inner type intact. - Key present with value
null: setsnullable: truewhile preserving non-null types observed in sibling items (yieldingstring | nullin TypeScript orz.string().nullable()in Zod). - Identifier Sanitization: object names pass through
toPascalCaseIdentifier(prefixingTif an identifier starts with a digit), while Rust and Python fields normalize camelCase keys withtoSnakeCaseIdentifierand annotate#[serde(rename = "...")]or PydanticField(alias=...)when needed.
3. Six Target Emitters from One AST
Decoupling inference (inferSchemaFromValue) from emission lets all six languages share identical structural nesting rules:
- TypeScript & Zod: Nested sub-objects are hoisted top-down via deterministic name hints (
`${parentName}${toPascalCaseIdentifier(key)}`) asexport interface/export typedeclarations or composablez.object(...)schemas with exportedz.infer<typeof Schema>types. - JSON Schema Draft 2020-12: Populates
requiredstrictly from keys withoptional === falseand maps nullable fields to two-type union arrays. - Go, Rust Serde & Python Pydantic v2: Emits Go structs with
json:"field,omitempty"tags, Rust structs derivingSerialize, Deserialize, and Pydantic v2BaseModeldefinitions withOptional[...]annotations.
4. Related Client-Side Developer Utilities
When inspecting raw payloads before generating types, pair the JSON to TypeScript & Schema Generator with the browser-local JSON Formatter & Validator, JSON Diff comparator, and HAR Sanitizer inside Sunasty Developer Tools.