encoding/json

encoding/json default float64 numbers, UseNumber, unknown fields, trailing values, and missing versus null pointer fields.

encoding/json is the standard-library JSON encoder and decoder. It is not a third-party package, and it is not a language built-in. Import the path "encoding/json"; there is no top-level package named json in the standard library.

This page documents how numbers land in any, how to reject unknown struct fields, how to require exactly one JSON value, and how a pointer field records a missing or null value. It does not cover custom MarshalJSON implementations or the experimental encoding/json/v2 package.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
json.Unmarshal, json.Decoder.UseNumber, json.NumberDecode JSON numbers into float64 by default when the destination is any. UseNumber keeps the original decimal text so large integers can be parsed as int64.
Decoder.DisallowUnknownFields and trailing dataReject unknown struct fields with DisallowUnknownFields. After a successful Decode, a second Decode must return io.EOF when the input should contain exactly one JSON value.
Pointer fields and json.UnmarshalFor a fresh struct, a pointer field stays nil when the JSON field is absent or null. A supplied zero produces a non-nil pointer to zero.

Default float64 and UseNumber

When a JSON number is decoded into an any (or into a map[string]any field), the default type is float64. Integers larger than 2^53 cannot be represented exactly in IEEE-754 binary64, so a value such as 9007199254740993 is rounded.

Decoder.UseNumber() stores that number as a json.Number, which is a string alias, instead. Call Int64, Float64, or String on the Number when you need a concrete value. Unmarshal itself has no UseNumber option; use a Decoder for this behavior.

json.Unmarshal, json.Decoder.UseNumber, json.Number

func Unmarshal(data []byte, v any) error
func NewDecoder(r io.Reader) *Decoder
func (dec *Decoder) UseNumber()
func (dec *Decoder) Decode(v any) error
type Number string
func (n Number) Int64() (int64, error)

Decode JSON numbers into float64 by default when the destination is any. UseNumber keeps the original decimal text so large integers can be parsed as int64.

ParameterDescription
data / rThe JSON input as bytes for Unmarshal, or as an io.Reader for a Decoder.
vA pointer to the destination value. Decoding into any stores bool, float64, string, []any, map[string]any, or nil.

Returns: Unmarshal and Decode return nil on success. Number.Int64 returns the integer value or a syntax or range error.

Errors

  • error — Syntax errors, type errors, and I/O errors from the reader. Decode returns io.EOF when no more values remain.
  • 9007199254740993 is 2^53 + 1. As float64 it becomes 9.007199254740992e+15, which is 2^53, not the original integer.
  • UseNumber must be called before Decode. It does not convert values that have already been decoded as float64.
go
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func main() {
	var value any
	if err := json.Unmarshal([]byte(`{"n":9007199254740993}`), &value); err != nil {
		panic(err)
	}
	n := value.(map[string]any)["n"]
	fmt.Printf("%T %v\n", n, n)

	dec := json.NewDecoder(strings.NewReader(`{"n":9007199254740993}`))
	dec.UseNumber()
	if err := dec.Decode(&value); err != nil {
		panic(err)
	}
	num := value.(map[string]any)["n"].(json.Number)
	i, err := num.Int64()
	fmt.Printf("%T %s %d %v\n", num, num.String(), i, err)
}

Expected output

float64 9.007199254740992e+15
json.Number 9007199254740993 9007199254740993 <nil>

Related: JSON Diff tool, JSON to Go, json.Number

Official documentation →

Unknown fields and trailing JSON

By default, Unmarshal and Decode ignore object keys that do not match a struct field. Decoder.DisallowUnknownFields changes that for a struct destination and returns an error that names the unexpected key.

A second Decode is the supported way to require exactly one JSON value. It returns io.EOF when the input is exhausted, including trailing whitespace. A second value is a successful Decode, not EOF. Unmarshal is stricter in a different way: trailing whitespace is allowed, but a second top-level value is an error.

Decoder.DisallowUnknownFields and trailing data

func (dec *Decoder) DisallowUnknownFields()
func (dec *Decoder) Decode(v any) error
func Unmarshal(data []byte, v any) error

Reject unknown struct fields with DisallowUnknownFields. After a successful Decode, a second Decode must return io.EOF when the input should contain exactly one JSON value.

ParameterDescription
decA Decoder created with json.NewDecoder. DisallowUnknownFields applies to later Decode calls on that decoder.
vThe destination. DisallowUnknownFields is effective when decoding into a struct.

Returns: Decode returns nil for a successful value, io.EOF when no further value is present, or another error for invalid input, unknown fields, or I/O failure.

Errors

  • unknown field — Decode reports json: unknown field "name" when DisallowUnknownFields is set and the destination is a struct.
  • io.EOF — Returned by a later Decode when the reader has no additional JSON value.
  • Unmarshal trailing value — json.Unmarshal rejects a second top-level value with invalid character '{' after top-level value, but it accepts trailing whitespace.
  • This example keeps the original Go reference recipe and its section id, then shows how Unmarshal treats a second value.
  • DisallowUnknownFields does not reject duplicate keys. Two "port" keys in one object are still accepted.
  • The accepted() helper returns true only when the first Decode succeeds and the second Decode is io.EOF.
go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"strings"
)

func accepted(input string) bool {
	decoder := json.NewDecoder(strings.NewReader(input))
	decoder.DisallowUnknownFields()

	var config struct {
		Port int `json:"port"`
	}
	if err := decoder.Decode(&config); err != nil {
		return false
	}

	var extra any
	return decoder.Decode(&extra) == io.EOF
}

func main() {
	fmt.Println(accepted(`{"port":80}`))
	fmt.Println(accepted(`{"port":80,"unknown":true}`))
	fmt.Println(accepted(`{"port":80} {"port":81}`))
	fmt.Println(json.Unmarshal([]byte(`{"port":80}  `), new(any)))
	fmt.Println(json.Unmarshal([]byte(`{"port":80}{"port":81}`), new(any)))
}

Expected output

true
false
false
<nil>
invalid character '{' after top-level value

Related: Original recipe on the Go overview

Official documentation →

Missing fields, null, and zero

JSON object keys that are absent leave a struct field at its zero value. For a pointer field on a freshly allocated struct, that zero value is nil. The JSON literal null also sets a pointer field to nil, so a pointer alone cannot tell those two inputs apart.

A present numeric zero unmarshals into a non-nil pointer to 0. If you need to distinguish a missing key from an explicit null, inspect the raw object or use json.RawMessage.

Pointer fields and json.Unmarshal

func Unmarshal(data []byte, v any) error

For a fresh struct, a pointer field stays nil when the JSON field is absent or null. A supplied zero produces a non-nil pointer to zero.

  • This example keeps the original Go reference recipe and its section id, and adds an explicit null input so the two nil cases are visible together.
  • Reuse of a struct value is a different situation: a previously set pointer is not reset to nil merely because a later payload omits the field.
go
package main

import (
	"encoding/json"
	"fmt"
)

type Config struct {
	Port *int `json:"port"`
}

func main() {
	for _, input := range []string{"{}", `{"port":null}`, `{"port":0}`} {
		var config Config
		if err := json.Unmarshal([]byte(input), &config); err != nil {
			panic(err)
		}
		if config.Port == nil {
			fmt.Println("port missing or null")
		} else {
			fmt.Println("port:", *config.Port)
		}
	}
}

Expected output

port missing or null
port missing or null
port: 0

Related: Original recipe on the Go overview

Official documentation →