A Go package for building, marshaling, and validating JSON Schema documents with support for Draft 4, Draft 7, and Draft 2020-12.
go get github.com/genelet/jsonschema- Zero dependencies: Pure Go implementation using only the standard library
- Multi-draft support: Compatible with JSON Schema Draft 4, Draft 7, and Draft 2020-12
- Round-trip fidelity: Parse and re-serialize schemas without data loss
- Boolean schemas: Full support for
true/falseschema literals - Validation: Schema structure validation with configurable rules
- Helper functions: Pre-built constructors for common schema patterns
package main
import (
"encoding/json"
"fmt"
"github.com/genelet/jsonschema/builder"
)
func main() {
// Create a simple string schema
schema := builder.NewStringSchema(nil, builder.IntPtr(100), "")
schema.Title = "Username"
schema.Description = "A user's login name"
// Marshal to JSON
output, _ := json.MarshalIndent(schema, "", " ")
fmt.Println(string(output))
}Output:
{
"type": "string",
"title": "Username",
"description": "A user's login name",
"maxLength": 100
}schema := builder.NewObjectSchema(
map[string]*builder.Schema{
"name": builder.NewStringSchema(nil, nil, ""),
"age": builder.NewIntegerSchema(builder.Float64Ptr(0), builder.Float64Ptr(150)),
"email": builder.NewEmailSchema(),
},
[]string{"name", "email"}, // required fields
)// Schema that allows everything
trueSchema := builder.NewBooleanTrueSchema()
// Schema that allows nothing
falseSchema := builder.NewBooleanFalseSchema()
// Check schema type
if schema.IsBooleanTrueSchema() {
fmt.Println("Allows all values")
}// Configure for Draft 4 (uses "id" instead of "$id", "definitions" instead of "$defs")
schema := &builder.Schema{Type: builder.TypeObject}
schema.SetDraft4Compatible()
// Configure for Draft 7
schema.SetDraft7Compatible()schema := &builder.Schema{
Type: builder.TypeString,
MinLength: builder.IntPtr(10),
MaxLength: builder.IntPtr(5), // Invalid: min > max
}
result := builder.ValidateSchema(schema)
if !result.Valid {
for _, err := range result.Errors {
fmt.Printf("Error in %s: %s\n", err.Field, err.Message)
}
}
// Check for warnings (deprecated features, etc.)
if result.HasWarnings() {
for _, warn := range result.Warnings {
fmt.Printf("Warning: %s\n", warn.Message)
}
}jsonData := []byte(`{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}`)
var schema builder.Schema
if err := json.Unmarshal(jsonData, &schema); err != nil {
log.Fatal(err)
}
// Access schema fields
fmt.Printf("Type: %s\n", schema.Type)
fmt.Printf("Required: %v\n", schema.Required)builder.IntPtr(10) // *int
builder.Float64Ptr(3.14) // *float64
builder.StringPtr("text") // *string
builder.BoolPtr(true) // *bool| Function | Description |
|---|---|
NewStringSchema(min, max, pattern) |
String with optional constraints |
NewIntegerSchema(min, max) |
Integer with optional bounds |
NewNumberSchema(min, max) |
Number with optional bounds |
NewBooleanTypeSchema() |
Boolean type schema |
NewArraySchema(items) |
Array with items schema |
NewObjectSchema(props, required) |
Object with properties |
NewNullSchema() |
Null type schema |
| Function | Format |
|---|---|
NewEmailSchema() |
email |
NewURISchema() |
uri |
NewURIReferenceSchema() |
uri-reference |
NewDateTimeSchema() |
date-time |
NewDateSchema() |
date |
NewTimeSchema() |
time |
NewUUIDSchema() |
uuid |
NewHostnameSchema() |
hostname |
NewIPv4Schema() |
ipv4 |
NewIPv6Schema() |
ipv6 |
| Function | Description |
|---|---|
NewPositiveIntegerSchema() |
Integer > 0 |
NewNonNegativeIntegerSchema() |
Integer >= 0 |
NewEnumSchema(values...) |
Enumeration |
NewConstSchema(value) |
Constant value |
NewRefSchema(ref) |
Reference to another schema |
The Schema struct supports all JSON Schema keywords:
- Metadata:
$id,$schema,$comment,$anchor,$defs - Type:
type(single or array),enum,const - Strings:
minLength,maxLength,pattern,format - Numbers:
minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf - Arrays:
items,prefixItems,additionalItems,minItems,maxItems,uniqueItems,contains - Objects:
properties,patternProperties,additionalProperties,required,propertyNames,minProperties,maxProperties - Composition:
allOf,anyOf,oneOf,not - Conditionals:
if,then,else - References:
$ref,$dynamicRef
The package includes comprehensive tests using the official JSON Schema Test Suite:
# Run all tests
go test ./...
# Run with coverage
go test -cover ./...
# Run specific draft tests
go test -run TestDraft4 ./builder/...
go test -run TestDraft7 ./builder/...
go test -run TestDraft2020 ./builder/...MIT License