Skip to content

JSON to JSON Schema Generator — JavaScript 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 JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// json-to-schema — JSON instance → draft-07 JSON Schema inferrer. JavaScript
// port (canonical TS: src/lib/json-to-schema.ts; Go twin: cli/json-to-schema).
// Given one JSON instance, infers a draft-07 style schema: the integer vs
// number split (2.0 is an integer — JSON has no int type), objects list every
// key as required with keys sorted, homogeneous arrays merge to a single item
// type, mixed arrays become a sorted `type` array (other keywords dropped),
// empty arrays carry no `items` key, and strictObjects adds
// "additionalProperties": false to every object schema. Empty or
// whitespace-only input yields empty output, not an error; parse failures
// surface the parser's message (or "Invalid JSON"). Output text is
// JSON.stringify(schema, null, 2) parity. Never throws.
'use strict';

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

function scalarType(v) {
  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 kinds. One kind keeps
// that type; anything else becomes a sorted unique `type` array. Other
// keywords are dropped — a merged schema describes shape, not constraints.
function inferArrayItems(v) {
  const set = new Set();
  for (const el of v) set.add(scalarType(el));
  return set.size === 1 ? { type: [...set][0] } : { type: [...set].sort() };
}

function infer(v, strict) {
  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 = {};
    for (const key of keys) properties[key] = infer(v[key], strict);
    const schema = { type: 'object', properties, required: keys };
    if (strict) schema.additionalProperties = false;
    return schema;
  }
  return { type: scalarType(v) };
}

function jsonToSchema(raw, options = {}) {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  let value;
  try {
    value = JSON.parse(text);
  } catch (e) {
    return { output: '', error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
  const schema = { $schema: DRAFT_07, ...infer(value, options.strictObjects === true) };
  return { output: JSON.stringify(schema, null, 2), error: null };
}

// Example:
// jsonToSchema('{"b": 1, "a": [1, "x"]}')
// → {
//   "$schema": "http://json-schema.org/draft-07/schema#",
//   "type": "object",
//   "properties": { "a": { "type": "array", "items": { "type": ["integer", "string"] } }, "b": { "type": "integer" } },
//   "required": ["a", "b"]
// }

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 →