Skip to content

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

"""json-to-schema — JSON instance → draft-07 JSON Schema inferrer. Python 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 strict_objects 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. Output text is
JSON.stringify(schema, null, 2) parity (json.dumps indent=2, ensure_ascii
off). Never raises — errors travel in the result dict.
"""
import json
import math

DRAFT_07 = "http://json-schema.org/draft-07/schema#"


def scalar_kind(v):
    """Six scalar kinds; bool checked before int (bool subclasses int)."""
    if isinstance(v, bool):
        return "boolean"
    if v is None:
        return "null"
    if isinstance(v, int):
        return "integer"
    if isinstance(v, float):
        # JSON has no int type: an integral double (2.0, 1e2) is an integer.
        return "integer" if math.isfinite(v) and v == math.floor(v) else "number"
    if isinstance(v, list):
        return "array"
    if isinstance(v, dict):
        return "object"
    return "string"


def array_items(v):
    """Union of element kinds: one kind keeps it, else a sorted type list."""
    kinds = sorted({scalar_kind(el) for el in v})
    if len(kinds) == 1:
        return {"type": kinds[0]}
    return {"type": kinds}


def infer(v, strict):
    if isinstance(v, list):
        if not v:
            return {"type": "array"}  # empty array carries no `items` key
        return {"type": "array", "items": array_items(v)}
    if isinstance(v, dict):
        keys = sorted(v.keys())
        properties = {k: infer(v[k], strict) for k in keys}
        schema = {"type": "object", "properties": properties, "required": keys}
        if strict:
            schema["additionalProperties"] = False
        return schema
    return {"type": scalar_kind(v)}


def json_to_schema(raw, strict_objects=False):
    text = raw.strip()
    if not text:  # empty input is NOT an error — the tool shows nothing
        return {"output": "", "error": None}
    try:
        value = json.loads(text)
    except ValueError as e:
        return {"output": "", "error": str(e) or "Invalid JSON"}
    schema = {"$schema": DRAFT_07}
    schema.update(infer(value, strict_objects is True))
    return {"output": json.dumps(schema, indent=2, ensure_ascii=False), "error": None}


# Example:
# json_to_schema('{"b": 1, "a": [1, "x"]}')["output"]
# → {
#   "$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 →