Skip to content

JSON to JSON Schema Generator — TypeScript source

Infer a draft-07 JSON Schema from any JSON document: scalar types, array item merging, all-keys-required objects and an optional strict mode. Runs locally in your browser with a shareable link.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the JSON to JSON Schema tool (slug: json-to-schema). Infers
// a draft-07 style schema from one JSON instance. The inference rules below
// are the contract a Go CLI twin must reproduce: integer vs number split,
// array item merging, sorted `type` arrays for mixed arrays, all-keys-required
// objects, and the optional additionalProperties:false strictness flag.
export interface JsonToSchemaOptions {
  /** Emit `"additionalProperties": false` on every object schema. Default false. */
  strictObjects?: boolean;
}

export type JsonToSchemaResult =
  | { output: string; error: null }
  /** Empty or whitespace-only input is NOT an error — the tool shows nothing. */
  | { output: ''; error: null }
  | { output: ''; error: string };

type JsonValue = null | boolean | number | string | JsonValue[] | { [k: string]: JsonValue };

type Schema = Record<string, unknown>;

const DRAFT_07 = 'http://json-schema.org/draft-07/schema#';

function scalarType(v: JsonValue): 'array' | 'boolean' | 'integer' | 'null' | 'number' | 'object' | 'string' {
  if (Array.isArray(v)) return 'array';
  if (v === null) return 'null';
  if (typeof v === 'boolean') return 'boolean';
  if (typeof v === 'number') return Number.isInteger(v) ? 'integer' : 'number';
  if (typeof v === 'object') return 'object';
  return 'string';
}

/** Infer an array's `items` schema: union of the element types. Same single
 * type keeps that type; anything else becomes a sorted unique `type` array
 * (draft-07 allows type arrays). Other keywords are dropped — a merged schema
 * describes shape, not constraints — so scalarType alone suffices per element
 * (the Go twin's scalarKind does the same). */
function inferArrayItems(v: JsonValue[]): Schema {
  const set = new Set<string>();
  for (const el of v) set.add(scalarType(el));
  return set.size === 1 ? { type: [...set][0] } : { type: [...set].sort() };
}

function infer(v: JsonValue, strict: boolean): Schema {
  if (Array.isArray(v)) {
    if (v.length === 0) return { type: 'array' };
    return { type: 'array', items: inferArrayItems(v) };
  }
  if (v !== null && typeof v === 'object') {
    const keys = Object.keys(v).sort();
    const properties: Record<string, Schema> = {};
    for (const key of keys) properties[key] = infer(v[key], strict);
    const schema: Schema = { type: 'object', properties, required: keys };
    if (strict) schema.additionalProperties = false;
    return schema;
  }
  return { type: scalarType(v) };
}

/** Infer a draft-07 schema for the given JSON text, pretty-printed 2-space. */
export function jsonToSchema(raw: string, options: JsonToSchemaOptions = {}): JsonToSchemaResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  let value: JsonValue;
  try {
    value = JSON.parse(text) as JsonValue;
  } catch (e) {
    return { output: '', error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
  const schema: Schema = { $schema: DRAFT_07, ...infer(value, options.strictObjects === true) };
  return { output: JSON.stringify(schema, null, 2), error: null };
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →