jsonschema

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 11 Imported by: 4 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

jsonschema-infer

A Go library for inferring JSON Schema from JSON samples. This library analyzes multiple JSON documents and automatically generates a JSON Schema that describes their structure, types, and patterns.

Features

Type inference
  • ✅ Infer basic types: string, boolean, number, integer, null
  • ✅ Nested objects: full support for deeply nested object structures
  • ✅ Arrays: treats all array items as the same type and infers their schema
  • ✅ Arrays of objects: infers schemas for complex array items with optional fields
  • ✅ Flexible root types: supports objects, arrays, and primitives at root level
  • ✅ Multiple types: union types when a field has varying types across samples
Field presence
  • ✅ Optional fields: fields appearing in all samples → required; some samples → optional
  • ✅ Null → optional: a field whose value is null in any sample is treated as optional, without polluting the inferred type
  • ✅ Const detection: if a primitive field always has the same value, the schema includes "const" for that value
Format detection
  • ✅ Unified format detection: all formats detected using the same FormatDetector mechanism
  • ✅ Built-in formats: datetime (ISO 8601), email, UUID, IPv4, IPv6, URL (HTTP/HTTPS/FTP/FTPS)
  • ✅ Custom format detectors: register user-defined format detection functions
  • ✅ Disable built-in formats: opt out for full control over format detection
Configuration
  • ✅ Predefined types: override inference for specific fields (e.g., created_at as DateTime)
  • ✅ Schema versions: Draft 06 and Draft 07 (default)
  • ✅ Examples: optional first-value capturing per field (disabled by default)
  • ✅ Max samples limit: cap the number of samples processed
  • ✅ Indented output: configurable JSON indentation via WithIndent
Performance & API
  • ✅ Lazy schema building: schema built on demand, cached between samples — no per-sample overhead
  • ✅ O(1) memory per field: format candidates eliminated eagerly; no string buffering
  • ✅ AddParsedSample: skip JSON parsing when you've already decoded the document
  • ✅ GenerateTo(io.Writer): write schema directly to any writer without an intermediate string
  • ✅ Thread-safe: all methods safe for concurrent use — call AddParsedSample from multiple goroutines
  • ✅ Load/Resume: load a previously generated schema and continue adding samples

Requirements

  • Go 1.25 or higher

Installation

go get github.com/JLugagne/jsonschema-infer

Documentation

Quick Start

Basic Usage
package main

import (
    "fmt"
    "github.com/JLugagne/jsonschema-infer"
)

func main() {
    // Create a new generator
    generator := jsonschema.New()

    // Add JSON samples
    generator.AddSample(`{"name": "John", "age": 30, "active": true}`)
    generator.AddSample(`{"name": "Jane", "age": 25, "active": false}`)
    generator.AddSample(`{"name": "Bob", "age": 35}`)

    // Generate the schema
    schema, err := generator.Generate()
    if err != nil {
        panic(err)
    }

    fmt.Println(schema)
}

Output:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    },
    "active": {
      "type": "boolean"
    }
  },
  "required": ["name", "age"]
}

Note: active is not in required because it doesn't appear in all samples.

Predefined Types

Configure specific fields to have predefined types:

generator := jsonschema.New(
    jsonschema.WithPredefined("created_at", jsonschema.DateTime),
    jsonschema.WithPredefined("updated_at", jsonschema.DateTime),
)

generator.AddSample(`{"id": 1, "created_at": "2023-01-15T10:30:00Z"}`)
generator.AddSample(`{"id": 2, "created_at": "2023-02-20T14:45:00Z"}`)

schema, _ := generator.Generate()

Available predefined types:

  • DateTime - string with date-time format
  • String - string type
  • Boolean - boolean type
  • Number - number type
  • Integer - integer type
  • Array - array type
  • Object - object type
Examples

The library can capture the first observed value as an example for each field:

// Enable example capturing
generator := jsonschema.New(jsonschema.WithExamples())

By default, example capturing is disabled to save memory and keep schemas compact.

Arrays of Objects

The library handles arrays of objects and detects optional fields within array items:

generator := jsonschema.New()

generator.AddSample(`{
    "users": [
        {"id": 1, "name": "John", "email": "john@example.com"},
        {"id": 2, "name": "Jane"}
    ]
}`)

generator.AddSample(`{
    "users": [
        {"id": 3, "name": "Bob", "email": "bob@example.com"}
    ]
}`)

schema, _ := generator.Generate()

The resulting schema will show that email is optional in the array items since it doesn't appear in all objects.

Load and Resume

Load a previously generated schema and continue adding samples:

// Generate initial schema
generator1 := jsonschema.New()
generator1.AddSample(`{"name": "John", "age": 30}`)
schemaJSON, _ := generator1.Generate()

// Later, load the schema and add more samples
generator2 := jsonschema.New()
err := generator2.Load(schemaJSON)
if err != nil {
    panic(err)
}

// Add new samples with additional fields
generator2.AddSample(`{"name": "Jane", "age": 25, "email": "jane@example.com"}`)

// Generate updated schema
updatedSchema, _ := generator2.Generate()
Get Current Schema

Retrieve the current schema as a Schema object after any sample:

generator := jsonschema.New()
generator.AddSample(`{"name": "John"}`)

// Get the current schema as an object (not JSON string)
schema := generator.GetCurrentSchema()

// Access properties
fmt.Println(schema.Type) // "object"
fmt.Println(schema.Properties["name"].Type) // "string"

Building and Testing

Build
go build

Or use the Makefile:

make build
Test
go test -v

Or use the Makefile:

make test
Test with Coverage
make test-coverage

This generates coverage.html which you can open in a browser.

Architecture

The library uses a tree-based recursive architecture:

  • SchemaNode: Each node represents a part of the JSON structure

    • Handles only primitives (string, number, boolean, null)
    • Delegates to child nodes for complex types (arrays, objects)
    • Accumulates observations across all samples
  • Lazy Schema Building: Schema is built on demand when Generate() or GetCurrentSchema() is called

    • No redundant work while adding samples
    • Result is cached and reused until the next sample invalidates it
    • Can still inspect schema evolution via GetCurrentSchema() at any time
  • Optional Field Detection: Tracks how many times each field appears

    • Fields appearing in all samples → required
    • Fields appearing in some samples → optional

More Examples

See the examples/ directory for runnable examples:

  • basic - Basic type inference and optional fields
  • arrays - Arrays of objects with optional fields
  • datetime - Automatic datetime detection
  • predefined - Configuring predefined types
  • load_resume - Loading and resuming schemas
  • nested - Deeply nested structures
  • incremental - Watching schema evolution

Run all examples:

cd examples
./run-examples.sh

Comparison with Other Libraries

This library is unique in the Go ecosystem for sample-based JSON schema inference. Similar functionality exists in other languages:

Key advantages of jsonschema-infer:

  • ✅ Pure Go implementation
  • ✅ Incremental schema updates
  • ✅ Load/resume capability
  • ✅ Tree-based recursive architecture
  • ✅ Optional field frequency tracking

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

License

[Specify your license here]

Notes

  • The library uses Go's standard encoding/json package for JSON parsing
  • All array items are treated as having the same schema (merged together)
  • Multiple type detection is supported (e.g., a field that's sometimes string, sometimes number)

Documentation

Overview

Package jsonschema provides automatic JSON Schema generation from JSON samples.

This library analyzes multiple JSON documents and automatically generates a JSON Schema that describes their structure, types, and patterns. It uses an incremental, tree-based approach to build schemas that evolve as more samples are observed.

Overview

The jsonschema package allows you to:

  • Infer JSON schemas from one or more JSON samples
  • Detect optional vs required fields based on sample frequency
  • Automatically identify datetime patterns in strings
  • Configure predefined types for specific fields
  • Load and resume from previously generated schemas
  • Handle complex nested structures with arrays and objects

Basic Usage

The simplest way to use the library is to create a Generator, add JSON samples, and generate the resulting schema:

generator := jsonschema.New()
generator.AddSample(`{"name": "John", "age": 30}`)
generator.AddSample(`{"name": "Jane", "age": 25}`)
schema, err := generator.Generate()
if err != nil {
    log.Fatal(err)
}
fmt.Println(schema)

Type Inference

The library automatically infers the following JSON Schema types:

  • string: for text values
  • integer: for whole numbers
  • number: for floating-point numbers
  • boolean: for true/false values
  • array: for arrays (with item schema inference)
  • object: for objects (with recursive property inference)
  • null: for null values

When a field has multiple types across samples, the schema will include all observed types as an array.

Optional vs Required Fields

Fields are marked as required only if they appear in ALL samples. If a field appears in some but not all samples, it will be defined in the schema but not listed in the "required" array:

generator := jsonschema.New()
generator.AddSample(`{"name": "John", "age": 30}`)
generator.AddSample(`{"name": "Jane"}`)  // no age
schema, _ := generator.Generate()
// Result: only "name" is required, "age" is optional

Arrays

Arrays are handled by merging all observed items into a single schema. The library treats all array items as having the same type and generates a unified schema:

generator := jsonschema.New()
generator.AddSample(`{"tags": ["go", "json"]}`)
generator.AddSample(`{"tags": ["schema", "inference"]}`)
schema, _ := generator.Generate()
// Result: tags is array of strings

For arrays of objects, the library detects which fields are required across all observed array items:

generator := jsonschema.New()
generator.AddSample(`{"users": [{"id": 1, "name": "John", "email": "john@example.com"}]}`)
generator.AddSample(`{"users": [{"id": 2, "name": "Jane"}]}`)  // no email
schema, _ := generator.Generate()
// Result: id and name are required in array items, email is optional

Format Detection

The library uses a unified format detection mechanism. All formats (built-in and custom) are detected using FormatDetector functions: func(string) bool

Built-in formats are automatically registered:

  • date-time: ISO 8601 datetime strings (e.g., "2023-01-15T10:30:00Z")
  • email: Email addresses (e.g., "user@example.com")
  • uuid: UUIDs v1-v5 (e.g., "550e8400-e29b-41d4-a716-446655440000")
  • ipv4: IPv4 addresses (e.g., "192.168.1.1")
  • ipv6: IPv6 addresses (e.g., "2001:0db8:85a3::8a2e:0370:7334")
  • uri: URLs with HTTP, HTTPS, FTP, FTPS schemes (e.g., "https://example.com")

Custom formats can be registered using WithCustomFormat:

isHexColor := func(s string) bool {
    return len(s) == 7 && s[0] == '#' && /* ... */
}
generator := jsonschema.New(
    jsonschema.WithCustomFormat("hex-color", isHexColor),
)
generator.AddSample(`{"color": "#FF5733"}`)
schema, _ := generator.Generate()
// Result: color has type "string" and format "hex-color"

Built-in formats can be disabled if you want full control:

generator := jsonschema.New(jsonschema.WithoutBuiltInFormats())

All string values in a field must match for a format to be applied.

Predefined Types

You can configure specific fields to have predefined types, which override automatic type inference:

generator := jsonschema.New(
    jsonschema.WithPredefined("created_at", jsonschema.DateTime),
    jsonschema.WithPredefined("updated_at", jsonschema.DateTime),
)
generator.AddSample(`{"created_at": "2023-01-15T10:30:00Z"}`)
schema, _ := generator.Generate()
// Result: created_at is guaranteed to be string with date-time format

Available predefined types:

  • DateTime: string with date-time format
  • String: string type
  • Boolean: boolean type
  • Number: number type
  • Integer: integer type
  • Array: array type
  • Object: object type

Schema Versions

You can choose which JSON Schema draft version to generate. The library supports Draft 06 and Draft 07 (default):

// Generate Draft 06 schema
generator := jsonschema.New(jsonschema.WithSchemaVersion(jsonschema.Draft06))
generator.AddSample(`{"name": "John", "age": 30}`)
schema, _ := generator.Generate()
// Result: $schema is "http://json-schema.org/draft-06/schema#"

// Generate Draft 07 schema (default)
generator2 := jsonschema.New()  // or WithSchemaVersion(Draft07)
generator2.AddSample(`{"name": "Jane", "age": 25}`)
schema2, _ := generator2.Generate()
// Result: $schema is "http://json-schema.org/draft-07/schema#"

For the features used by this library, Draft 06 and Draft 07 are functionally equivalent. The main difference is the $schema URL in the output.

If you need to create an empty schema with a specific version (without using the Generator), use NewSchemaWithVersion:

schema := jsonschema.NewSchemaWithVersion(jsonschema.Draft06)
// schema.Schema is "http://json-schema.org/draft-06/schema#"

Note: For schema inference from samples, always use Generator with New() and AddSample(). The NewSchemaWithVersion function is only for creating empty schema structures.

Examples

The library can capture the first observed value for each field and include it as an example in the generated schema. By default, example capturing is disabled. To enable it, use the WithExamples option:

generator := jsonschema.New(jsonschema.WithExamples())
generator.AddSample(`{"name": "John"}`)
// Result: name field will have example: "John"

Lazy Schema Building

The schema is built on demand when Generate() or GetCurrentSchema() is called, not after every AddSample(). This avoids expensive O(N) tree traversals during bulk ingestion. The result is cached and reused until the next sample invalidates it.

If you parse JSON yourself (e.g. with json.Decoder), use AddParsedSample to skip re-parsing inside the library:

dec := json.NewDecoder(reader)
for dec.More() {
    var v interface{}
    dec.Decode(&v)
    generator.AddParsedSample(v)  // no double-parse
}
schema, _ := generator.Generate()

You can still inspect the evolving schema at any point via GetCurrentSchema():

generator := jsonschema.New()
generator.AddSample(`{"name": "John"}`)
schema1 := generator.GetCurrentSchema()
fmt.Printf("After 1 sample: %+v\n", schema1)

generator.AddSample(`{"name": "Jane", "age": 25}`)
schema2 := generator.GetCurrentSchema()
fmt.Printf("After 2 samples: %+v\n", schema2)

Loading and Resuming

You can load a previously generated schema and continue adding samples to it. This is useful for evolving schemas over time:

// Initial schema generation
generator1 := jsonschema.New()
generator1.AddSample(`{"name": "John", "age": 30}`)
schemaJSON, _ := generator1.Generate()

// Later, load and continue
generator2 := jsonschema.New()
err := generator2.Load(schemaJSON)
if err != nil {
    log.Fatal(err)
}
generator2.AddSample(`{"name": "Jane", "age": 25, "email": "jane@example.com"}`)
updatedSchema, _ := generator2.Generate()
// Result: schema now includes optional "email" field

Nested Structures

The library fully supports nested objects and arrays at any depth:

generator := jsonschema.New()
generator.AddSample(`{
    "company": {
        "name": "Acme Corp",
        "employees": [
            {"name": "Alice", "role": "Engineer"},
            {"name": "Bob", "role": "Designer"}
        ]
    }
}`)
schema, _ := generator.Generate()
// Result: fully nested schema with company.employees as array of objects

Architecture

The library uses a tree-based recursive architecture:

  • Each SchemaNode represents a part of the JSON structure
  • Nodes handle only primitives (string, number, boolean, null)
  • Complex types (arrays, objects) delegate to child nodes
  • All observations are accumulated across samples
  • Schema is built lazily (on demand) and cached between calls

This design keeps the code maintainable by limiting complexity to simple primitives within well-defined scopes.

Requirements

Go 1.25 or higher is required:

go build
go test

The library uses Go's standard encoding/json package for JSON parsing.

Error Handling

Methods that can fail return errors:

  • AddSample() returns an error if the JSON is invalid
  • Generate() returns an error if no samples have been added
  • Load() returns an error if the schema JSON is invalid or not an object schema

Always check errors to ensure reliable schema generation.

Limitations

Current limitations:

  • All array items are treated as having the same schema (no tuple support)
  • No validation constraints (min/max, length)
  • Only JSON Schema draft-07 output format
  • No enum detection for fields with limited value sets
  • Sample count tracking is approximate after loading schemas

Performance Considerations

  • Schema is built lazily — no overhead during sample ingestion.
  • Use AddParsedSample when you already hold a decoded interface{} value to avoid a second json.Unmarshal call.
  • For very large sample sets, set a limit with WithMaxSamples to cap the number of samples processed.

Thread Safety

The Generator is thread-safe. AddSample, AddParsedSample, Generate, and GetCurrentSchema can all be called concurrently from multiple goroutines.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CustomFormat

type CustomFormat struct {
	Name     string
	Detector FormatDetector
}

CustomFormat represents a user-defined format with its detector function

type FormatDetector

type FormatDetector func(string) bool

FormatDetector is a function that checks if a string matches a custom format

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator generates JSON schemas from JSON samples

func New

func New(opts ...Option) *Generator

New creates a new Generator with optional configuration

func (*Generator) AddParsedSample added in v0.3.0

func (g *Generator) AddParsedSample(data interface{}) error

AddParsedSample adds an already-parsed JSON value to the generator and updates the schema. Use this when you have already unmarshalled the JSON yourself (e.g. via json.Decoder) to avoid parsing the same document twice. Thread-safe: can be called concurrently from multiple goroutines.

func (*Generator) AddSample

func (g *Generator) AddSample(jsonData string) error

AddSample adds a JSON sample to the generator and updates the schema. Thread-safe: can be called concurrently from multiple goroutines.

func (*Generator) Generate

func (g *Generator) Generate() (string, error)

Generate generates a JSON schema from the accumulated samples. Thread-safe: can be called concurrently from multiple goroutines.

func (*Generator) GenerateTo added in v0.3.0

func (g *Generator) GenerateTo(w io.Writer) error

GenerateTo writes the JSON schema directly to w. This avoids allocating an intermediate string when writing to a file, HTTP response body, or any other io.Writer. Thread-safe: can be called concurrently from multiple goroutines.

func (*Generator) GetCurrentSchema

func (g *Generator) GetCurrentSchema() *Schema

GetCurrentSchema returns the current schema as a Schema object. This can be called after each AddSample to see the evolving schema. Thread-safe: can be called concurrently from multiple goroutines.

func (*Generator) Load

func (g *Generator) Load(schemaJSON string) error

Load loads a previously generated JSON schema and initializes the generator This allows continuing to add samples to an existing schema Thread-safe: can be called concurrently from multiple goroutines

type Option

type Option func(*Generator)

Option is a functional option for configuring the Generator

func WithCustomFormat

func WithCustomFormat(formatName string, detector FormatDetector) Option

WithCustomFormat registers a custom format detector Custom formats are checked after built-in formats (date-time, email, uuid, ipv6, ipv4, uri) The formatName will be used as the value for the "format" field in the schema

func WithExamples added in v0.2.0

func WithExamples() Option

WithExamples enables capturing examples in the schema By default, examples are disabled

func WithIndent added in v0.3.0

func WithIndent(indent string) Option

WithIndent sets the indentation string used when marshaling the schema to JSON. A common value is " " (two spaces) or "\t" (tab). By default, output is compact (no indentation).

func WithMaxSamples

func WithMaxSamples(max int) Option

WithMaxSamples sets the maximum number of samples to process Once this limit is reached, AddSample will return nil but do nothing

func WithPredefined

func WithPredefined(fieldName string, typeValue PredefinedType) Option

WithPredefined sets a predefined type for a field name

func WithSchemaVersion added in v0.2.0

func WithSchemaVersion(version SchemaVersion) Option

WithSchemaVersion sets the JSON Schema draft version Defaults to Draft07 if not specified

func WithoutBuiltInFormats

func WithoutBuiltInFormats() Option

WithoutBuiltInFormats disables all built-in format detectors Use this if you want to provide your own complete set of format detectors

type PredefinedType

type PredefinedType string

PredefinedType represents a predefined type for a field

const (
	DateTime PredefinedType = "datetime"
	String   PredefinedType = "string"
	Boolean  PredefinedType = "boolean"
	Number   PredefinedType = "number"
	Integer  PredefinedType = "integer"
	Array    PredefinedType = "array"
	Object   PredefinedType = "object"
)

type Schema

type Schema struct {
	Schema               string             `json:"$schema,omitempty"`
	Type                 any                `json:"type,omitempty"` // can be string or []string
	Properties           map[string]*Schema `json:"properties,omitempty"`
	Items                *Schema            `json:"items,omitempty"`
	Required             []string           `json:"required,omitempty"`
	Format               string             `json:"format,omitempty"`
	Const                any                `json:"const,omitempty"`
	Example              any                `json:"example,omitempty"`
	AdditionalProperties *bool              `json:"additionalProperties,omitempty"`
}

Schema represents a JSON Schema

func NewSchema

func NewSchema() *Schema

NewSchema creates a new Schema with default Draft 07 values.

func NewSchemaWithVersion added in v0.2.0

func NewSchemaWithVersion(version SchemaVersion) *Schema

NewSchemaWithVersion creates a new Schema with the specified JSON Schema version. This is useful when you need an empty schema structure with a specific version set.

For schema inference from samples, use Generator instead:

gen := jsonschema.New(jsonschema.WithSchemaVersion(Draft06))
gen.AddSample(`{"your": "data"}`)
schemaJSON, _ := gen.Generate()

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON marshaling for Schema

type SchemaNode

type SchemaNode struct {
	// contains filtered or unexported fields
}

SchemaNode represents a node in the schema tree Each node handles only primitives and delegates to children for complex types

func NewSchemaNode

func NewSchemaNode() *SchemaNode

NewSchemaNode creates a new schema node

func (*SchemaNode) ObserveValue

func (n *SchemaNode) ObserveValue(value interface{}, examplesEnabled bool, formats []CustomFormat)

ObserveValue updates this node with a new observed value. formats is the list of format detectors to evaluate against string values; passing the same slice on every call is fine — it is read-only here.

func (*SchemaNode) ToSchema

func (n *SchemaNode) ToSchema() *Schema

ToSchema converts this node to a JSON Schema. Format detection state is already fully up-to-date in candidateFormats — no formats argument is needed here.

type SchemaVersion added in v0.2.0

type SchemaVersion string

SchemaVersion represents a JSON Schema draft version

const (
	// Draft06 represents JSON Schema Draft 06
	Draft06 SchemaVersion = "http://json-schema.org/draft-06/schema#"
	// Draft07 represents JSON Schema Draft 07 (default)
	Draft07 SchemaVersion = "http://json-schema.org/draft-07/schema#"
)

Directories

Path Synopsis
examples
arrays command
basic command
datetime command
incremental command
load_resume command
nested command
predefined command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址