Documentation
¶
Overview ¶
Package jsonx provides a generic, strongly-typed JSON decoder with rich, actionable error messages. It wraps encoding/json and surfaces line/column positions, context snippets, and sentinel errors that callers can test with errors.Is.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrBadlyJSON is returned when the input is not valid JSON // (syntax error or unexpected end of input). ErrBadlyJSON = jsonxErr("badly-formed JSON in the body") // ErrBadJSONType is returned when a JSON value cannot be decoded into the // target Go type (type mismatch). ErrBadJSONType = jsonxErr("incorrect JSON type in the body") // ErrEmptyBody is returned when the reader contains no bytes. ErrEmptyBody = jsonxErr("body must not be empty") // ErrBodyUnknownKey is returned when the JSON object contains a key that // does not map to any field in the target struct. ErrBodyUnknownKey = jsonxErr("unknown key in the body") // ErrBodySizeLimit is returned when an http.MaxBytesReader limit is hit // while reading the body. ErrBodySizeLimit = jsonxErr("body size limit exceeded") // ErrBodyValue is returned when the input contains more than one top-level // JSON value (e.g., two objects back-to-back). ErrBodyValue = jsonxErr("body must contain a single JSON value") )
Sentinel errors returned by ReadJSONAs. Use errors.Is to test for them.
Functions ¶
func Decoder ¶ added in v1.0.1
func Decoder[T any]() decoder[T]
Decoder returns a new strict decoder for type T. Chain Lenient() to relax unknown-field rejection before calling From / FromBytes.
Example — strict (equivalent to ReadJSONAs):
val, err := jsonx.Decoder[MyType]().From(r) val, err := jsonx.Decoder[MyType]().FromBytes(data)
Example — lenient (partial struct, test helper, schema introspection):
val, err := jsonx.Decoder[MyType]().Lenient().From(r) val, err := jsonx.Decoder[MyType]().Lenient().FromBytes(data)
func ReadJSONAs ¶
ReadJSONAs decodes r into T and returns the typed value.
This is a strict convenience wrapper around Decoder[T]().From(r). For configurable behaviour (e.g. allowing unknown fields or decoding from []byte) use the Decoder builder directly:
jsonx.Decoder[T]().From(r) jsonx.Decoder[T]().FromBytes(data) jsonx.Decoder[T]().Lenient().From(r)
Strict semantics:
- Unknown fields → ErrBodyUnknownKey
- Empty body → ErrEmptyBody
- Multiple values → ErrBodyValue
- Syntax error → ErrBadlyJSON + "line N col M (near …)"
- Type mismatch → ErrBadJSONType + field + expected Go type + JSON token
- Size limit → ErrBodySizeLimit (only when http.MaxBytesReader is used)
All returned errors wrap the relevant sentinel so errors.Is works:
val, err := jsonx.ReadJSONAs[MyType](r)
if errors.Is(err, jsonx.ErrBadlyJSON) { ... }
Types ¶
This section is empty.