JSON
encoding/json is the most used package in a Go service, and it is lax by default. Here are its rules from real runs, the strict form for a request body, and encoding/json/v2, which is no longer an experiment in Go 1.27.
- 1Decode into a typed struct. A number in any is a float64, and a float64 holds 53 bits.
- 2Decode is lax: it ignores unknown names, matches any case, and stops after one value.
- 3omitempty asks if the value is empty. omitzero asks if it is the zero value.
- 4Go 1.27 ships encoding/json/v2, and the old API now runs on it. New code should use v2.
package main
import (
"encoding/json"
"fmt"
)
func main() {
body := []byte(`{"id": 90071992547409931}`)
var v map[string]any2
json.Unmarshal(body, &v)
fmt.Printf("%.0f\n", v["id"])
out, _ := json.Marshal(v)3
fmt.Println(string(out))
}- 1Valid JSON, and a valid int64. It is 2 to the power 53, plus 1.
- 2With no type to guide it, Decode stores every number as a float64.
- 3The damage is permanent: a proxy that decodes and encodes changes the ID.
| decode into | recorded output | status |
|---|---|---|
| map[string]any | {"id":9007199254740992} | Wrong ID |
| struct, int64 field | {"id":9007199254740993} | Exact |
- A float64 has 53 bits of mantissa. Above 2 to the power 53, it cannot hold every integer.
- No error appears. The value is only a little wrong, so a test with small IDs passes.
- A JavaScript client has the same limit, because its numbers are float64 too.
- Snowflake-style IDs are larger than this limit.
An ID above 2 to the power 53 loses digits in a float64. I decode into int64, and I send IDs as strings to JavaScript clients.
| JSON | Go value in any |
|---|---|
| number | float64 |
| number, with UseNumber | json.Number |
| string | string |
| true, false | bool |
| array | []any |
| object | map[string]any |
| null | nil |
- Decode into any only for data with an unknown shape.
- A typed struct costs 3.2 µs. The same bytes into any cost 8.9 µs.
- Fields that are not in the struct are skipped: decoding one field costs 1.9 µs.
In any, a number is a float64, an array is []any, and an object is map[string]any. For digits I call UseNumber.
- encoding/json keeps its behaviour. Only the text of errors may differ.
- The build setting GOEXPERIMENT=nojsonv2 restores the old engine, for now.
- jsontext is the level for tokens: a proxy or a formatter can use it alone.
In Go 1.27 the old API is the v2 engine with v1 options. Behaviour stays, but the error text can change, so I never match on it.
| tag | effect | status |
|---|---|---|
| json:"name" | The wire name. A rename in Go cannot change the API. | Approved |
| json:"id,string" | A number as a JSON string. Safe for JavaScript. | Approved |
| json:"at,omitzero" | Omits the zero value, or what IsZero reports. | Approved |
| json:"-" | Never in the JSON. Use it for hashes and internal data. | Approved |
| json:"a,omitempty" | Omits false, 0, nil and empty. A real 0 disappears. | Strings, slices, maps |
| unexported field | Ignored in both directions. A tag on it has no effect. | Export it to encode it |
| json:"id" twice | Same-depth fields with one name cancel each other. | Not approved |
go vet checks the tag syntax and reports a repeated name.
Every field in an API type has a tag, because the wire name is a contract and a Go rename must not change it.
// User shows each tag option once.
type User struct {
ID int64 `json:"id,string"1`
Name string `json:"name"`
Email string `json:"email,omitempty"`
Age *int2 `json:"age,omitempty"`
Tags []string `json:"tags"3`
Created time.Time `json:"created,omitzero"4`
Hash string `json:"-"`
token string5
}
// NewUser sets Tags, so that the field encodes as [] and not null.
func NewUser(id int64, name, token string) User {
return User{ID: id, Name: name, Tags: []string{}6, token: token}
}- 1Encodes "9007199254740993" with quotes. Decoding accepts only the quoted form.
- 2nil is absent. A pointer to 0 stays in the output.
- 3No omit option: this field is always present.
- 4omitempty would print year 1 here. See panel F.
- 5Unexported, so JSON never reads or writes it.
- 6A nil slice would encode as null.
An optional number is a pointer, so that absent and 0 stay different. A list starts as an empty slice, so clients get [] and not null.
| value of the field | v1 omitempty | omitzero, v1 and v2 | v2 omitempty |
|---|---|---|---|
| int 0 | Omitted | Omitted | {"v":0} |
| string "" | Omitted | Omitted | Omitted |
| bool false | Omitted | Omitted | {"v":false} |
| nil pointer | Omitted | Omitted | Omitted |
| pointer to 0 | {"v":0} | {"v":0} | {"v":0} |
| nil slice | Omitted | Omitted | Omitted |
| empty slice | Omitted | {"v":[]} | Omitted |
| nil map | Omitted | Omitted | Omitted |
| empty map | Omitted | {"v":{}} | Omitted |
| zero struct | {"v":{"X":0}} | Omitted | {"v":{"X":0}} |
| zero time.Time | {"v":"0001-01-01T00:00:00Z"} | Omitted | {"v":"0001-01-01T00:00:00Z"} |
| Maybe{} with IsZero | {"v":{"Set":false}} | Omitted | {"v":{"Set":false}} |
- Use omitzero for time.Time, for structs, and for any type with an IsZero method.
- An empty slice stays under omitzero, because only nil is the zero value. Use that to tell "no list" from "empty list".
- With both options, the field is omitted if either rule says so.
omitzero is the rule for structs and time, since Go 1.24. In v2, omitempty looks at the JSON, so a 0 stays.
// Status is an enum with a text form, so it also works as a map key.
type Status int
// The order states.
const (
StatusOpen Status = iota
StatusPaid
)
var statusNames = []string{"open", "paid"}
// MarshalText has a value receiver, so every Status encodes.
func (s Status) MarshalText()1 ([]byte, error) {
if s < 0 || int(s) >= len(statusNames) {
return nil, fmt.Errorf("status %d: unknown", int(s))
}
return []byte(statusNames[s]), nil
}
// UnmarshalText rejects a name that is not in the list.
func (s *Status) UnmarshalText(2b []byte) error {
i := slices.Index(statusNames, string(b))
if i < 0 {
return fmt.Errorf("status %q: unknown", b)
}
*s = Status(i)
return nil
}
// Cents encodes as a decimal string, so no float touches money.
type Cents int64
// MarshalJSON writes 1250 as "12.50".
func (c Cents) MarshalJSON()3 ([]byte, error) {
sign := ""
if c < 0 {
sign, c = "-", -c
}
return fmt.Appendf(nil, `"%s%d.%02d"`, sign, c/100, c%100), nil
}
// UnmarshalJSON reads "12.50" and rejects other shapes.
func (c *Cents) UnmarshalJSON(b []byte) error {
if string(b) == "null"4 {
return nil
}
var s string
if err := json.Unmarshal(b, &s)5; err != nil {
return fmt.Errorf("cents: %w", err)
}
whole, frac, ok := strings.Cut(s, ".")
if !ok || len(frac) != 2 {
return fmt.Errorf("cents: %q needs 2 decimals", s)
}
n, err := strconv.ParseInt(whole+frac, 10, 64)
if err != nil {
return fmt.Errorf("cents: %w", err)
}
*c = Cents(n)
return nil
}- 1Text form: JSON quotes it, and map keys use it too. MarshalJSON cannot do map keys in the v1 API.
- 2A pointer receiver: the method must change the value.
- 3A value receiver, so a value in an interface or a map still encodes this way.
- 4The rule for an Unmarshaler: null does nothing.
- 5Decode the outer JSON with the package. Do not trim quotes by hand.
MarshalText gives an enum one form for values and map keys. Marshal methods use value receivers, and Unmarshal methods use pointers.
// Audit is shared by many documents.
type Audit struct {
CreatedBy string `json:"created_by"`
Updated time.Time `json:"updated,omitzero"`
}
// Doc embeds Audit, so its fields sit at the top level.
type Doc struct1 {
Audit
Title string `json:"title"`
}- 1Audit has no field name or tag, so its fields sit at the top level of Doc.
| rule | status |
|---|---|
| Embed plain structs to share fields | Approved |
| Name the field to keep it nested: Audit Audit | Approved |
| Embed time.Time or a type with Marshal methods | The method replaces the parent |
| Embed two types with one field name | Both fields disappear |
| Marshal method with a pointer receiver | Skipped on a plain value in v1 |
| []byte for binary data | Base64 string |
The drill runs each of these. A shallower field wins over a deeper one.
Embedding flattens the fields into the parent. I check that the embedded type has no Marshal method, because that method takes over the parent.
// SumArray reads a JSON array of orders one element at a time,
// so memory stays flat for any array length.
func SumArray(r io.Reader) (int64, error) {
dec := json.NewDecoder(r)
if _, err := dec.Token()1; err != nil {
return 0, fmt.Errorf("open bracket: %w", err)
}
var total int64
for dec.More()2 {
var o payload.Order3
if err := dec.Decode(&o); err != nil {
return 0, fmt.Errorf("order: %w", err)
}
total += o.Total
}
if _, err := dec.Token(); err != nil {
return 0, fmt.Errorf("close bracket: %w", err)
}
return total, nil
}
// WriteLines writes one JSON value per line (NDJSON).
func WriteLines(w io.Writer, orders []payload.Order) error {
buf := bufio.NewWriter(w)4
enc := json.NewEncoder(buf)
for i := range orders {
if err := enc.Encode(&orders[i])5; err != nil {
return fmt.Errorf("order %d: %w", i, err)
}
}
if err := buf.Flush()6; err != nil {
return fmt.Errorf("flush: %w", err)
}
return nil
}- 1Reads the opening bracket, so Decode can start on each element.
- 2True until the closing bracket.
- 3A fresh value per element. A reused value keeps fields from the last element.
- 4An Encoder writes once per value. The buffer joins those writes.
- 5Encode adds a newline after each value, so this output is NDJSON.
- 6Without this, the last bytes stay in the buffer.
| method | peak heap | time |
|---|---|---|
| ReadFile and Unmarshal | 97 MB | 0.36 s |
| Decoder, one element at a time | 3.1 MB | 0.45 s |
An array of 100,000 orders, 30 MB on disk, median of 3 runs.
- Unmarshal needs the whole input in memory, and then the whole result.
- A Decoder holds one element and its read buffer.
- Use a stream for exports, imports and any array without a size limit.
- A Decoder is not a validator: it stops with an error at the first bad element, after the earlier ones have run.
A Decoder reads one element at a time, so memory stays flat. For a large export I write NDJSON through a bufio.Writer.
// ReadStrict accepts exactly one JSON value with known fields.
func ReadStrict(r io.Reader, v any) error {
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()1
if err := dec.Decode(v); err != nil {
return fmt.Errorf("%w: %v", ErrInvalid, err)
}
if err := dec.Decode(&struct{}{})2; !errors.Is(err, io.EOF)3 {
return fmt.Errorf("%w: data after the value", ErrInvalid)
}
return nil
}- 1A typo in a name is an error, not a default value.
- 2A second Decode must hit the end of the input. Any other result means data follows.
- 3Trailing spaces and newlines still pass.
Wrap the body in MaxBytesReader first (see G16). Decoding is not validation: null and an empty object pass here, so check the values next.
A strict decoder rejects unknown names and trailing data. Then a client typo returns 400 and does not change the meaning of a request.
// Event carries a payload whose shape depends on Type.
type Event struct {
Type string `json:"type"`
Data json.RawMessage1 `json:"data"`
}
// Paid is the payload of a "paid" event.
type Paid struct {
Order string `json:"order"`
Cents int64 `json:"cents"`
}
// Refund is the payload of a "refund" event.
type Refund struct {
Order string `json:"order"`
Reason string `json:"reason"`
}
// ReadEvent decodes the envelope, then only the payload it needs.
func ReadEvent(b []byte) (any, error) {
var e Event
if err := json.Unmarshal(b, &e); err != nil {
return nil, fmt.Errorf("envelope: %w", err)
}
switch e.Type2 {
case "paid":
return decodeAs[Paid](e.Data)
case "refund":
return decodeAs[Refund](e.Data)
}
return nil, fmt.Errorf("event type %q: unknown", e.Type)
}
func decodeAs[T any]3(b []byte) (T, error) {
var v T
if err := json.Unmarshal(b, &v); err != nil {
return v, fmt.Errorf("payload: %w", err)
}
return v, nil
}- 1Stores the raw bytes of this field. The syntax is checked; the shape is not.
- 2One function per event type, and a clear error for an unknown type.
- 3One generic helper avoids a decode block in each case.
RawMessage keeps the bytes of a field, so I read the envelope first and decode the payload only when I know its type.
body {"by": 2}
readJSON
Decoder, as in the build kit
Accepted, By = 2
ReadStrict
v1 API, strict
Accepted, By = 2
ReadV2
v2 API, RejectUnknownMembers
Accepted, By = 2
- Each reader decodes into a struct with one field: By int with the tag json:"by".
- Pick "Typo in a name": the kit accepts it, and By is 0.
- Pick "null" or "Empty object": all three accept it. The handler must still check that By is set.
- Read the error text of the v2 column: it names a Go type, so do not send it to a client.
- Package v2 prints "cannot" or "unable to", chosen once per process, so that no code can depend on the text. This page shows one form.
A repeated name lets two parsers disagree about one request, so I prefer the v2 rule that rejects it.
// DecodeAny keeps every number as its original digits.
func DecodeAny(b []byte) (any, error) {
dec := json.NewDecoder(bytes.NewReader(b))
dec.UseNumber()1
var v any
if err := dec.Decode(&v); err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return v, nil
}
// Int64At reads one field of a decoded object as an int64.
func Int64At(v any, key string) (int64, error) {
obj, ok := v.(map[string]any)
if !ok {
return 0, fmt.Errorf("%T is not an object", v)
}
n, ok := obj[key].(json.Number)2
if !ok {
return 0, fmt.Errorf("%s is not a number", key)
}
return n.Int64()3
}- 1Numbers in any become json.Number, which holds the text.
- 2The type is now json.Number, so an assertion to float64 fails.
- 3Returns an error for a fraction or for a value out of range.
When the shape is unknown, UseNumber keeps the original digits, and I convert with Int64 or Float64 at the point of use.
| the client must see | Go field | tag |
|---|---|---|
| Always a list, maybe [] | []T, set to empty | json:"x" |
| A list, or no field | []T | omitempty |
| A number, 0 is valid, or no field | *int | omitempty |
| A time, or no field | time.Time | omitzero |
| A value or null | *T | json:"x" |
| the server must read | Go field | status |
|---|---|---|
| Present or absent | *T | Approved |
| Absent, null or a value | json.RawMessage | Check the bytes |
| Present, by zero value | T | 0 looks absent |
For a PATCH, absent means keep. A pointer field shows that, but it cannot tell null from absent, so I decide what null means.
| behaviour | input | v1 API | v2 API | option that restores v1 |
|---|---|---|---|---|
| Field names | {"NAME":"a"} into json:"name" | {Name:a} | {Name:} | MatchCaseInsensitiveNames |
| Nil slice | []int(nil) | null | [] | FormatNilSliceAsNull |
| Nil map | map[string]int(nil) | null | {} | FormatNilMapAsNull |
| omitempty on int 0 | omit{N: 0} | {} | {"n":0} | use omitzero in both |
| Repeated name | {"a":1,"a":2} | map[a:2] | error | jsontext.AllowDuplicateNames |
| Invalid UTF-8 | "a\xff" | "a�" | error | jsontext.AllowInvalidUTF8 |
| HTML characters | "<b>&" | "\u003cb\u003e\u0026" | "<b>&" | jsontext.EscapeForHTML |
| Array length | [1,2,3] into [2]int | [1 2] | error | UnmarshalArrayFromAnyLength |
| Byte array | [3]byte{1, 2, 3} | [1,2,3] | "AQID" | FormatByteArrayAsArray |
| Pointer-receiver method | value, not pointer | {"R":1} | "called" | CallMethodsWithLegacySemantics |
| time.Duration | 1500 ms | 1500000000 | error | FormatDurationAsNano |
| Decode over a slice element | [{"b":2}] over [{A:1}] | [{A:1 B:2}] | [{A:0 B:2}] | MergeWithLegacySemantics |
| null into a set int | null into 5 | 5 | 0 | MergeWithLegacySemantics |
| Struct with no exported field | struct{ x int } | {} | error | ReportErrorsWithLegacySemantics |
| Map key order | map with 8 keys, 200 runs | sorted by key | order varies | Deterministic |
In the v2 column, "error" means the call returned an error. The option names come from the encoding/json package documentation.
v2 is generally available in Go 1.27. Its defaults are strict, and each difference has an option, so I can move one rule at a time.
// ReadV2 is ReadStrict in the v2 API. It reads to EOF, so
// trailing data, unknown names and repeated names all fail.
func ReadV2(r io.Reader, v any) error {
err := jsonv2.UnmarshalRead(r, v,1
jsonv2.RejectUnknownMembers(true)2,
)
if err != nil {
return fmt.Errorf("%w: %v", ErrInvalid, err)
}
return nil
}
// Order keeps its ID as a string on the wire.
type Order struct {
ID int64 `json:"id,string"`
Tags []string `json:"tags"`
Taken time.Time `json:"taken,omitzero"`
}
// WriteV2 streams to w with no intermediate slice.
func WriteV2(w io.Writer, o Order) error {
if err := jsonv2.MarshalWrite(w, o)3; err != nil {
return fmt.Errorf("encode: %w", err)
}
return nil
}- 1Takes a Reader and options, with no Decoder object.
- 2The v2 form of DisallowUnknownFields.
- 3Writes to w directly, for a handler that writes JSON.
UnmarshalRead reads to the end of the input, so the trailing-data check is built in. One option turns on unknown-name errors.
| situation | status |
|---|---|
| New code | Use v2 |
| Existing code that works | Keep v1; it stays supported |
| Migrating a service | jsonv2.Marshal(v, jsonv1.DefaultOptionsV1()) |
| Clients expect null for empty lists | FormatNilSliceAsNull |
| time.Duration in an API type | Pick a form: v2 has no default |
| Depending on error text | It changes per process in v2 |
| Depending on map key order in v2 | Use Deterministic |
Engine change, same v1 API, same order: Unmarshal 5.1 µs before, 3.2 µs now. Marshal 1.2 µs before, 1.6 µs now.
New code uses v2. In an existing service I start with DefaultOptionsV1 and turn on one strict rule at a time.
| since | what changed | what it means here |
|---|---|---|
| 1.22 | Encoding writes \b and \f, not \u0008 and \u000c. | Output changed for those two characters. |
| 1.24 | The omitzero tag option, with IsZero support. UnmarshalTypeError.Field includes embedded structs. | time.Time can now be omitted with a tag. |
| 1.25 | encoding/json/v2 and jsontext as an experiment, behind GOEXPERIMENT=jsonv2. | You could test the new engine. It was off by default. |
| 1.27 | encoding/json/v2 and jsontext are available with no setting. encoding/json runs on the v2 engine. GOEXPERIMENT=nojsonv2 opts out, and the notes expect that to go in a future release. | Behaviour stays. Error text can change. Unmarshal is faster. |
| 1.27 | Changes since the experiment: the format and unknown tag options, DiscardUnknownMembers and SkipFunc are gone. The inline tag option is now embed. jsontext number accessors return errors. | Code written for the experiment needs edits. |
| when | the moment | what to do or say |
|---|---|---|
| build | You type readJSON from the K1 kit. | One Decode into a struct, wrapped as ErrInvalid. It is enough to pass, so move on. |
| build | The kit declares var body struct{ By int } with no tag. | It works because v1 matches the name By in any case. In v2, add json:"by". |
| build | A field is required. | Use a pointer, or check the zero value. Decode does not know about required fields. |
| build | The prompt returns a list. | Start with make, so an empty result is [] and not null. |
| talk | "What would you harden in readJSON?" | A size limit, DisallowUnknownFields, a trailing-data check, and a fixed client message for the error. |
| talk | "How do you add a field to an API?" | Readers must ignore unknown names, so strict decoding fits a public request body, not a response you read. |
| talk | "Why not float64 for money?" | Decimal fractions do not fit binary floats. Use integer cents, or a decimal string on the wire. |
| talk | "Is JSON the bottleneck?" | One order is 317 bytes and costs about 1.6 µs. Measure first, and compare with the database call. |
In the build I use the kit's readJSON. In the talk I name what it accepts by accident, and how I would close each gap.
0 of 12 known
Predict the output.
package main import ( "encoding/json" "fmt" ) type Stock struct { Item string `json:"item"` Count int `json:"count,omitempty"` Sold *int `json:"sold,omitempty"` } func main() { zero := 0 out, _ := json.Marshal(Stock{Item: "pen", Count: 0, Sold: &zero}) fmt.Println(string(out)) }Predict the output.
package main import ( "encoding/json" "fmt" "time" ) type A struct { At time.Time `json:"at,omitempty"` } type B struct { At time.Time `json:"at,omitzero"` } func main() { a, _ := json.Marshal(A{}) b, _ := json.Marshal(B{}) fmt.Println(string(a)) fmt.Println(string(b)) }Predict the output.
package main import ( "encoding/json" "fmt" ) func main() { var nilSlice []int empty := []int{} var nilMap map[string]int a, _ := json.Marshal(nilSlice) b, _ := json.Marshal(empty) c, _ := json.Marshal(nilMap) fmt.Println(string(a), string(b), string(c)) }Predict the output.
package main import ( "encoding/json" "fmt" ) type Req struct { Name string `json:"name"` } func main() { var a, b Req json.Unmarshal([]byte(`{"NAME": "upper"}`), &a) json.Unmarshal([]byte(`{"name": "lower", "nAmE": "last"}`), &b) fmt.Println(a.Name, b.Name) }Predict the output.
package main import ( "encoding/json" "fmt" "strings" ) type Req struct { Limit int `json:"limit"` } func main() { body := `{"limt": 10}` var a Req err := json.Unmarshal([]byte(body), &a) fmt.Println(a.Limit, err) var b Req dec := json.NewDecoder(strings.NewReader(body)) dec.DisallowUnknownFields() err = dec.Decode(&b) fmt.Println(b.Limit, err != nil) }Predict the output.
package main import ( "encoding/json" "fmt" "strings" ) type Req struct { N int `json:"n"` } func main() { body := `{"n": 1} {"n": 2} garbage` var a Req err := json.NewDecoder(strings.NewReader(body)).Decode(&a) fmt.Println(a.N, err) var b Req err = json.Unmarshal([]byte(body), &b) fmt.Println(b.N, err != nil) }Predict the output.
package main import ( "encoding/json" "fmt" "time" ) type Event struct { time.Time Name string `json:"name"` } func main() { e := Event{ Time: time.Date(2026, 3, 7, 9, 0, 0, 0, time.UTC), Name: "deploy", } out, _ := json.Marshal(e) fmt.Println(string(out)) }Predict the output.
package main import ( "encoding/json" "fmt" ) type A struct{ ID int } type B struct{ ID int } type Both struct { A B Title string `json:"title"` } type Outer struct { A ID string } func main() { x, _ := json.Marshal(Both{A{1}, B{2}, "t"}) y, _ := json.Marshal(Outer{A{1}, "top"}) fmt.Println(string(x)) fmt.Println(string(y)) }Predict the output.
package main import ( "encoding/json" "fmt" ) type Color struct{ R int } func (c *Color) MarshalJSON() ([]byte, error) { return []byte(`"custom"`), nil } func main() { c := Color{R: 1} a, _ := json.Marshal(c) b, _ := json.Marshal(&c) fmt.Println(string(a), string(b)) }Predict the output.
package main import ( "encoding/json" "fmt" ) type Blob struct { Data []byte `json:"data"` Raw []int8 `json:"raw"` } func main() { out, _ := json.Marshal(Blob{Data: []byte("hi"), Raw: []int8{104, 105}}) fmt.Println(string(out)) }Predict the output.
package main import ( "encoding/json" "fmt" ) type Config struct { Host string `json:"host"` Port int `json:"port"` Tags map[string]int `json:"tags"` } func main() { c := Config{Host: "a", Port: 80, Tags: map[string]int{"x": 1}} json.Unmarshal([]byte(`{"port": 443, "tags": {"y": 2}}`), &c) fmt.Println(c.Host, c.Port, c.Tags) }Predict the output.
package main import ( "encoding/json" "fmt" ) func main() { var v any json.Unmarshal([]byte(`{"n": 1, "ok": true, "l": [1], "o": {}, "s": "x", "z": null}`), &v) m := v.(map[string]any) for _, k := range []string{"n", "ok", "l", "o", "s", "z"} { fmt.Printf("%s=%T ", k, m[k]) } fmt.Println() _, isInt := m["n"].(int) fmt.Println(isInt) }
- Marshal
- 1.6 µs and 3 allocations; v2 API 1.6 µs.
- Unmarshal
- 3.2 µs and 9 allocations; v2 API 2.7 µs.
- into any
- 8.9 µs and 77 allocations.
- by hand
- 487 ns with strconv and no reflection, 3.2 times faster than Marshal.
- 2^53
- 9,007,199,254,740,992. Up to here, a float64 holds every integer exactly.
- new engine
- Unmarshal runs 1.6 times faster than the old one on this order.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.