json
A JSON library that delivers encoding/json semantics on a faster backend.
Features
encoding/json v1 semantics, held in place by a differential conformance
suite and three fuzz targets.
- Writes the same bytes as
encoding/json, not merely the same value.
- Reports failures with
encoding/json's own error types.
- Contains a backend panic on malformed input rather than letting it out.
What "same as encoding/json" means here
The output is byte for byte what encoding/json writes, so golden files, hashes
and signatures produced with the standard library keep working here. The
conformance suite and FuzzMarshalConformance compare raw bytes rather than
parsed values to keep that true.
Where the backend would mean something different, the value goes to
encoding/json instead of being papered over. Most of those are worked out from
the type, so the cost lands once per type rather than once per call:
- Map key types. Only string, integer and text-marshalling keys stay on the
backend. A pointer key makes it write an unquoted member name, which is not
valid JSON at all; float keys it rejects outright, while
encoding/json
accepts them from Go 1.27 on.
- Failures. The backend raises its own error types, and refuses a few values
encoding/json encodes, such as a nil slice of a type it cannot represent. A
failed call is therefore replayed through encoding/json and its outcome
returned. Only failures pay for it.
Byte agreement with a JSON encoder in some other language is a separate question
and is not promised, exactly as encoding/json does not promise it either.
Errors and partial state
Failures carry encoding/json's error types, so the usual inspection works:
var typeErr *stdjson.UnmarshalTypeError
if errors.As(err, &typeErr) {
// typeErr.Field, typeErr.Offset, ...
}
When Unmarshal reports an error the contents of the target are unspecified:
the backend applies part of a malformed document before giving up. Treat a
failed decode as having produced nothing.
Requirement
Also available: go.gh.ink/json/v2, which delivers encoding/json/v2
semantics and requires Go 1.27. The two are separate modules and develop
independently.
Usage
Marshal/Unmarshal
import "go.gh.ink/json"
var data YourSchema
// Marshal
output, err := json.Marshal(&data)
// Unmarshal
err := json.Unmarshal(output, &data)
Preheat
Compiles codecs ahead of their first use. It is a no-op on backends with nothing
to compile.
err := json.Preheat(reflect.TypeFor[YourSchema]())
err := json.PreheatMany([]reflect.Type{reflect.TypeFor[YourSchema]()})