Skip to content

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

// Package jsontoschema is the Go twin of CosmoDev's src/lib/json-to-schema.ts
// (dual source: the web lib is TypeScript, the CLI lib is Go — kept in
// lock-step). Pure + deterministic, never panics. The table-driven tests in
// json-to-schema_test.go share vectors with src/lib/json-to-schema.test.ts so
// the two implementations are held to the same contract.
//
// Given one JSON instance, the tool infers a draft-07 style schema. The
// inference rules are the contract: integer vs number split (2.0 is an
// integer), objects list every key as required with keys sorted, homogeneous
// arrays merge to a single item type, mixed arrays become a sorted `type`
// array, empty arrays carry no `items` key, and strict mode adds
// "additionalProperties": false to every object schema. Output text is
// JSON.stringify(schema, null, 2) parity — 2-space indent, no HTML escaping.
package jsontoschema

import (
	"bytes"
	"encoding/json"
	"math"
	"sort"
	"strings"
)

// Options configures JsonToSchema. The zero value (Options{}) matches the TS
// default (jsonToSchema(raw) with no options): objects stay open.
type Options struct {
	// StrictObjects emits "additionalProperties": false on every object
	// schema, mirroring opts.strictObjects (default false).
	StrictObjects bool
}

// Result mirrors the TS JsonToSchemaResult union: either an output with a
// null error, an empty output with a null error for empty input, or an empty
// output with a string error. Error is "" (zero value) standing in for the TS
// null case, so a zero Result means "empty input — the tool shows nothing".
type Result struct {
	Output string
	Error  string
}

// draft07 is the $schema every inferred schema carries.
const draft07 = "http://json-schema.org/draft-07/schema#"

// kind holds one JSON type name, or several for a merged (union) schema.
// MarshalJSON renders a single kind as a bare string (the common case) and
// several kinds as an array — draft-07 allows type arrays, exactly like the
// TS lib building { type: [...set].sort() }.
type kind []string

func (k kind) MarshalJSON() ([]byte, error) {
	if len(k) == 1 {
		return json.Marshal(k[0])
	}
	return json.Marshal([]string(k))
}

// items is an array's inferred `items` schema. The TS merge keeps ONLY the
// type — other keywords are dropped: a merged schema describes shape, not
// constraints.
type items struct {
	Type kind `json:"type"`
}

// schema mirrors the TS Schema object. Field order equals the TS key
// insertion order ({ $schema, type, items } / { $schema, type, properties,
// required, additionalProperties? }), so the marshaled text matches
// JSON.stringify byte for byte. Pointer fields + omitempty emit a key only
// when the TS lib would set one, while still rendering the empty
// "properties": {} / "required": [] that plain omitempty would drop.
type schema struct {
	Draft                *string            `json:"$schema,omitempty"`              // top level only
	Type                 kind               `json:"type,omitempty"`                 // always set
	Items                *items             `json:"items,omitempty"`                // arrays with ≥1 element
	Properties           *map[string]schema `json:"properties,omitempty"`           // objects, even empty
	Required             *[]string          `json:"required,omitempty"`             // objects, even empty
	AdditionalProperties *bool              `json:"additionalProperties,omitempty"` // strict mode only
}

// JsonToSchema infers a draft-07 schema for the given JSON text, pretty-printed
// with a 2-space indent (JSON.stringify(schema, null, 2) parity). It is the Go
// twin of jsonToSchema() in src/lib/json-to-schema.ts and must agree with it
// on every shared vector. Empty or whitespace-only input is NOT an error — it
// returns a zero Result (the tool shows nothing). Invalid JSON returns the
// parser's error message with empty output, never a panic.
func JsonToSchema(raw string, opts Options) Result {
	text := strings.TrimSpace(raw)
	if text == "" {
		return Result{}
	}
	var value any
	if err := json.Unmarshal([]byte(text), &value); err != nil {
		return Result{Error: err.Error()}
	}
	s := infer(value, opts.StrictObjects)
	draft := draft07
	s.Draft = &draft
	out, err := marshalPretty(s)
	if err != nil {
		return Result{Error: err.Error()}
	}
	return Result{Output: out}
}

// marshalPretty renders schema exactly like JSON.stringify(schema, null, 2):
// 2-space indent and NO HTML escaping (plain json.Marshal would turn
// `<`/`>`/`&` inside object keys into </>/&, which the TS lib
// never does). The Encoder's trailing newline is trimmed to match
// JSON.stringify exactly.
func marshalPretty(s schema) (string, error) {
	var b bytes.Buffer
	enc := json.NewEncoder(&b)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(s); err != nil {
		return "", err
	}
	return strings.TrimSuffix(b.String(), "\n"), nil
}

// scalarKind mirrors scalarType() in the TS lib: the JSON type name of any
// value, with the integer/number split (TS Number.isInteger: 2.0 → "integer";
// both languages parse JSON numbers as doubles, so the truncation test agrees
// on every input).
func scalarKind(v any) string {
	switch t := v.(type) {
	case nil:
		return "null"
	case bool:
		return "boolean"
	case string:
		return "string"
	case float64:
		if t == math.Trunc(t) {
			return "integer"
		}
		return "number"
	case []any:
		return "array"
	case map[string]any:
		return "object"
	default:
		return "null" // unreachable for JSON-decoded values
	}
}

// inferArrayItems merges an array's element schemas into a single `items`
// schema: the union of the element TYPES — one type stays a bare string,
// anything else becomes a sorted unique `type` array. Mirrors inferArrayItems
// in the TS lib (Set + default sort; the type names are lowercase ASCII, so
// JS sort order and Go sort.Strings agree).
func inferArrayItems(v []any) *items {
	set := make(map[string]bool, len(v))
	for _, el := range v {
		set[scalarKind(el)] = true
	}
	kinds := make([]string, 0, len(set))
	for k := range set {
		kinds = append(kinds, k)
	}
	sort.Strings(kinds)
	return &items{Type: kind(kinds)} // kind renders len==1 as a bare string
}

// infer builds the schema for one value, mirroring infer() in the TS lib.
// Object keys are sorted before recursion (Object.keys(v).sort()) — that both
// sorts `required` and, via Go's sorted map marshaling, the `properties` keys.
// strict propagates only through objects: the array items merge keeps just
// element types, so strictness does NOT reach inside `items`.
func infer(v any, strict bool) schema {
	switch t := v.(type) {
	case []any:
		s := schema{Type: kind{"array"}}
		if len(t) > 0 {
			s.Items = inferArrayItems(t)
		}
		return s
	case map[string]any:
		keys := make([]string, 0, len(t))
		for k := range t {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		properties := make(map[string]schema, len(t))
		for _, k := range keys {
			properties[k] = infer(t[k], strict)
		}
		s := schema{Type: kind{"object"}, Properties: &properties, Required: &keys}
		if strict {
			closed := false
			s.AdditionalProperties = &closed
		}
		return s
	default:
		return schema{Type: kind{scalarKind(v)}}
	}
}

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 →