Work with JSON Schema in Go

A practical review of validating and formatting JSON against a schema in Go: what each step changes, where meaning can shift, and when plain struct decoding is enough.

Using JSON Schema in Go usually means two related jobs: checking that incoming JSON satisfies a declared contract, and producing JSON that is readable and safe to pass along. Neither job is purely cosmetic. Some steps leave your data untouched, some change only whitespace, and some quietly change values, key order or escaping. This review explains which is which so you can judge whether a given workflow preserves what your use case needs.

Scope note: no tested library comparisons, benchmarks or version-specific test results were available for this article. Behavior described for Go's standard library reflects its documented design. Claims about third-party validators are kept general, and you should confirm draft support and maintenance status for any library before adopting it.

Is schema validation in Go the right fit for your use?

Schema validation is a good fit when the contract has to live outside your Go code: shared with other languages, published to API consumers, stored in configuration, or enforced on documents whose shape you do not fully control. The main benefit is a single, language-neutral description of what valid input looks like, with machine-readable errors when input does not match.

The decisive tradeoff is duplication. Your Go structs already describe a shape, and a separate schema describes it again. If the two drift apart, data can pass schema validation and still fail decoding, or decode cleanly while violating the schema. Generating a schema from structs, or structs from a schema, reduces drift but ties you to whatever that generator supports.

Plain struct decoding with explicit checks is often preferable when the JSON is only consumed by one Go service, the rules are simple (required fields, basic types, a few ranges), and nobody outside the codebase needs to read the contract. In that case, decoding with unknown fields disallowed plus a small validation function is easier to read and debug than an added schema layer.

What each step actually changes

The word "validate" is used loosely. In Go, json.Valid only checks that bytes are syntactically valid JSON; it knows nothing about required fields or types. Schema validation checks a decoded document against rules and returns errors, but does not modify the document. Formatting changes the bytes you store or display. Decoding changes the representation, and that is where meaning can shift.

Step | What changes | What stays the same
json.Valid | Nothing; returns true or false | All bytes
Schema validation | Nothing in the data; produces errors or annotations | Values, order, whitespace
json.Indent or MarshalIndent | Insignificant whitespace only | Values, key order of the input
json.Marshal of a map | Keys are sorted; <, > and & are escaped as \u003c, \u003e, \u0026; invalid UTF-8 is replaced with U+FFFD | Values for valid input
Unmarshal into a struct | Unknown fields are dropped silently unless DisallowUnknownFields is set; for duplicate keys, the last value wins | Fields that match the struct
Unmarshal into any (interface{}) | Numbers become float64, which can lose precision for large integers, unless the decoder uses UseNumber | Strings, booleans, nesting

The number conversion matters for schema work. Many validators operate on a decoded value rather than raw bytes. If a large integer ID is decoded as float64 before validation, an "integer" or exact-value check may be evaluated against a rounded number. Decoding with UseNumber, or passing raw bytes to a validator that accepts them, keeps the original digits.

dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()             // keep numbers as json.Number, not float64
dec.DisallowUnknownFields() // only applies when decoding into a struct

var doc any
if err := dec.Decode(&doc); err != nil {
	return err
}
// pass doc to your schema validator

String length is not what the reader sees

JSON Schema's minLength and maxLength are defined in terms of characters as RFC 8259 describes them, which in practice means Unicode code points. Go's len counts bytes, and neither measure matches what a person perceives as one character when combining marks or multi-code-point emoji are involved.

s := "e\u0301" // displays as one accented letter: e + combining acute accent
fmt.Println(len(s))                    // 3 (bytes)
fmt.Println(utf8.RuneCountInString(s)) // 2 (code points)

A family emoji built from three people joined by zero-width joiners is five code points but one visible symbol. A maxLength of 3 would reject it even though a user sees a single character. If your limits are meant for display width or user-perceived characters, a schema length rule alone will not express that; you need a separate check based on grapheme clusters, and you should test your chosen validator to confirm how it counts.

The format keyword is not formatting

In JSON Schema, "format" (for example "email" or "date-time") describes the semantic type of a string. It does not reformat anything. In drafts 2019-09 and 2020-12, format is treated as an annotation by default, so a validator may report it without rejecting non-matching values unless format assertion is enabled. Check your validator's setting rather than assuming format rules are enforced.

Will the output stay readable and usable after copying or sharing?

Indented JSON copies and pastes cleanly as plain text, because indentation is ordinary spaces or tabs and does not change meaning. The common readability surprise is HTML escaping: json.Marshal turns a literal "a<b" into "a\u003cb". Both decode to the same string, but the escaped form is harder for people to read in logs, diffs or pasted examples. If the output will not be embedded in HTML, an Encoder with SetEscapeHTML(false) keeps the characters literal. Note that Encoder.Encode adds a trailing newline.

enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", "  ")
_ = enc.Encode(map[string]string{"expr": "a<b"})
// {
//   "expr": "a<b"
// }

Key sorting on map output is helpful for stable diffs but means the output order will not match the input order. If reviewers compare a document against a schema or against a source file by position, reordering can make a correct document look changed. Struct output follows field declaration order instead.

Compatibility depends heavily on the schema draft. The $schema keyword identifies which draft a schema targets, and validators differ in which drafts they support and how completely. A schema that uses newer keywords may be silently ignored or rejected by a validator built for an older draft. When sharing schemas across teams or languages, state the draft explicitly and confirm each consumer supports it.

Validation error output is often written for developers, with JSON Pointer paths and keyword names. That is usable in logs but not for end users or non-technical reviewers. When errors are shown to people filling in a form or editing a config file, a plain-text equivalent is needed: a short sentence naming the field, what was expected and what was found. No documentation or scoped testing of specific assistive technologies was available here, so whether raw validator messages read well in a screen reader is an open question; plain sentences are the safer default.

Practical checklist

  • Use json.Valid for syntax only; do not treat it as schema validation.
  • Decode with UseNumber before validating if exact integers or decimals matter.
  • Set DisallowUnknownFields on struct decoding if extra fields should be errors.
  • Declare the schema draft and confirm your validator supports it.
  • Check whether format is asserted or only annotated in your validator.
  • Test length rules with combining marks and emoji if user-entered text is involved.
  • Turn off HTML escaping for human-facing output that is not embedded in HTML.
  • Provide plain-language error messages wherever people other than developers see them.

Open questions this review could not settle

No verified comparison of specific Go JSON Schema libraries, their draft coverage, error message quality or performance was available. Those details change between releases, so evaluate candidates against your own schemas and sample data, including edge cases such as large integers, Unicode strings and unknown fields, before committing to one.