Use JSON Schema in Go
How JSON Schema validation, decoding and formatting differ in Go, what each step changes in your data, and when plain struct decoding is enough.
Using JSON Schema in Go usually means one of three things: checking incoming JSON against a schema document, generating a schema from Go struct types, or decoding JSON into structs and treating that as validation. These are different operations. Some leave your data untouched. Others quietly reformat or reinterpret it. This review explains each one so you can judge whether the step you are adding keeps the meaning and readability your workflow needs.
Is JSON Schema validation the right fit for your Go project?
JSON Schema helps most when the contract must be shared beyond one Go program. Examples include an API consumed by clients in other languages, configuration files edited by people, and data exchanged between teams. A schema is a language-neutral document, so the same rules can be checked in Go, in an editor, and in other services.
The main tradeoff is that Go's standard library has no JSON Schema support. You depend on a third-party validator, and you maintain two descriptions of the same shape: the schema and your Go types. If they drift apart, a document can pass the schema and still fail to decode, or the reverse.
Decoding straight into structs with the standard library is often enough when:
- Only your own Go code consumes the data.
- The rules are mostly about field names and types.
- You can express the remaining checks, such as ranges or required combinations, in ordinary Go code after decoding.
Choose a schema when other tools or people need to read and enforce the same rules. Choose plain decoding when the contract lives entirely inside one Go codebase.
What each step actually changes
"Validate", "format" and "parse" are often used loosely in JSON tooling. In Go they map to distinct operations, and only some of them alter the stored characters.
| Operation | Changes stored bytes? | Can change meaning? | Notes |
| Well-formedness check (json.Valid) | No | No | Reports only whether the input is syntactically valid JSON |
| JSON Schema validation | No | No | Reports whether the instance satisfies the schema; the document itself is untouched |
| Indenting or compacting raw bytes (json.Indent, json.Compact) | Whitespace only | No | Keeps key order and number text as written |
| Decode then re-encode (Unmarshal then Marshal) | Yes | Possibly | Map keys are sorted, numbers may be rewritten, and some characters are escaped |
| Decoding into a struct | Not applicable; produces Go values | Possibly | Unknown fields are dropped silently unless you disallow them |
Validation reports; it does not repair
A JSON Schema validator returns a pass or fail result, usually with error locations. It does not rewrite the document. The schema keyword "default" is an annotation in the specification, so a validator does not insert missing values for you. If you need defaults applied, do it in Go after validation.
Behavior also depends on the schema draft. Draft-04, draft-06, draft-07, 2019-09 and 2020-12 differ in keyword names and semantics. In 2019-09 and 2020-12, the "format" keyword is treated as an annotation by default rather than an assertion. A schema that rejects a malformed email in one validator may therefore accept it in another. Declare the draft with "$schema" and check which drafts and format assertions your chosen library supports in its own documentation.
Re-encoding can alter what you send on
Decoding into a generic map and marshaling it again is the step most likely to change data unexpectedly. With the standard encoding/json package:
- Map keys are emitted in sorted order, so the original key order is lost.
- Numbers decoded into interface values become float64. This can lose precision for large integers and rewrites literals such as 2.50 as 2.5. Decoder.UseNumber keeps the original number text.
- The characters <, > and & inside strings are escaped as \u003c, \u003e and \u0026 by default. Encoder.SetEscapeHTML(false) turns this off.
- Invalid UTF-8 in strings is replaced with the Unicode replacement character when marshaling.
- When unmarshaling, duplicate keys are accepted and the last value wins. Struct field names are matched case-insensitively.
Here is an example of a round trip through a map with the default settings:
input: {"b":1,"a":2.50,"note":"a<b"}
output: {"a":2.5,"b":1,"note":"a\u003cb"}
Both lines are valid JSON and decode to equivalent values. The output is still not byte-identical to the input. This matters if anything downstream hashes, signs or diffs the raw text.
A standard-library baseline
Before adding a schema library, this pattern checks syntax and enforces a struct shape. It rejects fields the struct does not declare:
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
)
type Config struct {
Name string `json:"name"`
Retries int `json:"retries"`
}
func main() {
data, err := os.ReadFile("config.json")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if !json.Valid(data) {
fmt.Fprintln(os.Stderr, "not well-formed JSON")
os.Exit(1)
}
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
var cfg Config
if err := dec.Decode(&cfg); err != nil {
fmt.Fprintln(os.Stderr, "does not match Config:", err)
os.Exit(1)
}
fmt.Printf("%+v\n", cfg)
}
This does not check required fields. A missing "retries" silently becomes 0. It also does not check value ranges or patterns. Those gaps are what a JSON Schema adds, along with portability to tools outside Go.
If you only need readable output, reformat the raw bytes instead of re-marshaling. This changes whitespace only:
var out bytes.Buffer
if err := json.Indent(&out, data, "", " "); err != nil {
// input was not valid JSON
}
Will the result stay readable and usable after copying or sharing?
Indented and compact JSON are interchangeable for any compliant parser, so whitespace changes are safe to copy between tools. The visible differences that confuse people are mostly escape sequences such as \u003c. They are correct but harder to read, and someone editing by hand may not recognize them as equivalent to the original character.
Copying JSON or schemas out of rendered documents, chat tools or word processors is a common way to break them. Curly quotes, non-breaking spaces and invisible characters can replace the plain ASCII that JSON requires. Run json.Valid or your validator on pasted input rather than trusting that it looks right.
Validation does not touch string contents. Text with right-to-left characters or emoji passes through unchanged even if an editor or terminal displays it in an unexpected order. Display problems like these come from the viewer, not the data.
Keep a plain, unmodified copy of the original document whenever byte-for-byte fidelity matters. This applies to signed payloads, content-addressed storage, and audit records. Pass the original along and treat any reformatted or re-encoded version as a view for people, not a replacement.
Gaps in this review
No tested evidence about specific Go JSON Schema libraries was available for this article. It therefore makes no claims about which drafts a particular library supports, how fast it is, or what its error messages look like. Confirm those details in each library's documentation and with your own schemas. Likewise, no documentation or scoped tests were available on how screen readers or particular editors handle deeply nested or heavily escaped JSON. Treat accessibility in those environments as unverified and test it with the tools your readers actually use.