Skip to content

Go JSON unmarshalling for custom types

Unmarshalling turns JSON into Go values. Fix the stack overflow when UnmarshalJSON or MarshalJSON calls itself, with common errors and a test.

5 min read Updated
On this page

Unmarshalling

Unmarshalling turns encoded data, such as a JSON document, back into values in your program. Marshalling goes the other way: a value in memory becomes bytes you can store or send. In Go the encoding/json package does both with json.Marshal and json.Unmarshal, and a type can take over either step by implementing the Marshaler and Unmarshaler interfaces.

Spelling

Both spellings are correct. “Marshalling” with two l’s is British English and “marshaling” with one is American. Go’s standard library names use the single l (Marshaler, Unmarshaler), so you’ll often see both in the same code base.

Unmarshalling and deserialization

For JSON in Go the two words mean the same thing: decoding bytes into a value. Some texts keep them apart because in Java’s RMI, marshalling an object also records where to load its class code from. That distinction doesn’t apply to encoding/json.

Custom map types

If you’ve created your own custom type and want to use it in your JSON unmarshalling, you can do so by implementing the Unmarshaler interface. This works fine if your custom type is a struct but what if your custom type was a scalar or a map?

If you had a struct you would normally write the JSON tags as normal (this struct is a bit goofy looking - hence why I looked into unmarshalling directly into a map[string]string as you’ll see soon):

type KeyVals struct {
    KeyVals map[string]string `json:"keyvals,omitempty"`
}

And that would have been the end of it.

But if you had a scalar, a map, or any other custom type you would have to implement the Unmarshaler and perhaps also the Marshaler interface yourself.

My client had some code looking like this that I had to unmarshal some JSONB from PostgreSQL into:

type KeyVals map[string]string

The naive implementation is to use the json.Unmarshal and json.Marshal functions respectively like this:

func (kvs *KeyVals) MarshalJSON() ([]byte, error) {
	return json.Marshal(kvs)
}

func (kvs *KeyVals) UnmarshalJSON(data []byte) error {
	return json.Unmarshal(data, &kvs)
}

This however results in a stack overflow because of MarshalJSON and UnmarshalJSON being recursively and infinitely.

runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0xc0201614d0 stack=[0xc020160000, 0xc040160000]
fatal error: stack overflow

Solution

The solution is to create an intermediary variable to break the infinite loop. In UnmarshalJSON we also have to alias the type.

type KeyVals map[string]string

func (kvs *KeyVals) MarshalJSON() ([]byte, error) {
	v := map[string]string(*kvs)

	return json.Marshal(v)
}

func (kvs *KeyVals) UnmarshalJSON(data []byte) error {
	type temp KeyVals
	t := (*temp)(kvs)

	return json.Unmarshal(data, t)
}

Type definition, not alias

type temp KeyVals is strictly a type definition rather than an alias. It makes a new type with the same underlying map[string]string and none of KeyVals’s methods, so json.Unmarshal decodes into it as a plain map. A real alias, type temp = KeyVals, is only another name for KeyVals. It keeps UnmarshalJSON and loops again.

The new type’s name shows up in decoding errors, such as cannot unmarshal number into Go struct field temp.size of type string, so expect to see temp there.

Input and result

With the code above, this JSON:

{"colour": "blue", "size": "large"}

becomes KeyVals{"colour": "blue", "size": "large"}. A JSON null leaves the map nil and {} gives an empty map that isn’t nil, the same as a plain map[string]string.

Receivers

UnmarshalJSON needs a pointer receiver because it replaces the value. MarshalJSON is better with a value receiver. With a pointer receiver, json.Marshal only calls it when it can take the value’s address, so a plain KeyVals value or a KeyVals field in a struct passed by value gets the default encoding instead. For a map the output happens to be the same, which is why the version above still works, but for a type whose JSON differs from the default it’s a quiet bug.

This version works for values and pointers alike:

type KeyVals map[string]string

func (kvs KeyVals) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]string(kvs))
}

func (kvs *KeyVals) UnmarshalJSON(data []byte) error {
	type temp KeyVals

	return json.Unmarshal(data, (*temp)(kvs))
}

TextUnmarshaler

For a scalar that arrives as a JSON string, such as a level written as "high", implementing encoding.TextUnmarshaler is simpler. UnmarshalText gets the string without its quotes and never calls back into json.Unmarshal, so there’s no loop to break. encoding/json also uses it for map keys.

Common errors

These are the messages Go 1.27’s encoding/json gives for the usual mistakes:

  • json: cannot unmarshal number into Go struct field temp.size of type string: the JSON has a different type than the Go value, here a number where KeyVals only holds strings. Fix the input or use a Go type that accepts it, such as map[string]any.
  • unexpected end of JSON input: the data is empty or cut off.
  • invalid character 's' looking for beginning of value: the data isn’t JSON at all, such as form data or an HTML error page.
  • json: Unmarshal(non-pointer main.KeyVals): the value was passed instead of a pointer to it. Pass &kvs.
  • json: Unmarshal(nil *main.KeyVals): the pointer is nil. Declare a value and pass its address.
  • fatal error: stack overflow: the method ends up calling itself, as in the naive version above.

Testing

A custom type that only wraps a map should behave exactly like that map, which makes it easy to test. Decode the same inputs into both and compare, then encode both and compare again:

func TestKeyValsMatchesPlainMap(t *testing.T) {
	for _, input := range []string{`{"colour":"blue"}`, `{}`, `null`} {
		var kvs KeyVals
		if err := json.Unmarshal([]byte(input), &kvs); err != nil {
			t.Fatalf("unmarshal %s: %v", input, err)
		}

		var plain map[string]string
		if err := json.Unmarshal([]byte(input), &plain); err != nil {
			t.Fatalf("unmarshal %s into a map: %v", input, err)
		}

		if !reflect.DeepEqual(map[string]string(kvs), plain) {
			t.Errorf("unmarshal %s: got %v, want %v", input, kvs, plain)
		}

		got, err := json.Marshal(kvs)
		if err != nil {
			t.Fatalf("marshal %s: %v", input, err)
		}

		want, err := json.Marshal(plain)
		if err != nil {
			t.Fatalf("marshal %s as a map: %v", input, err)
		}

		if string(got) != string(want) {
			t.Errorf("marshal %s: got %s, want %s", input, got, want)
		}
	}
}

If either method called itself, the test binary would crash with the stack overflow, and go test reports that as a failure too.

Other languages

The same trap exists wherever you can customise decoding. In Swift, calling Self(from: decoder) inside your own init(from:) recurses the same way; decode the underlying [String: String] from decoder.singleValueContainer() instead. In Rust, serde’s #[serde(transparent)] on a newtype struct encodes and decodes it exactly like its single field, without a hand-written implementation.