Go JSON debugging

Go json.Unmarshal Errors

Go’s encoding/json package separates malformed JSON from data that parses but cannot fit the destination Go type. Understanding that distinction makes json.Unmarshal failures much faster to diagnose.

Quick answer

A SyntaxError means the JSON text itself is malformed. An UnmarshalTypeError means the JSON is syntactically valid but a value cannot be assigned to the destination Go field type.

Syntax errors

Messages such as invalid character ... looking for beginning of value often point to non-JSON input or malformed syntax. Inspect the raw body, especially when consuming HTTP responses.

Type mismatches

If JSON sends a string where the struct expects an int, Unmarshal can return an UnmarshalTypeError. Compare the payload to the struct tags and expected field types.

Unknown fields

json.Unmarshal normally ignores unknown object fields. For stricter API validation, use a Decoder and call DisallowUnknownFields so unexpected properties become errors.

Strict Go decoder example

dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&payload); err != nil {
    // inspect syntax/type/unknown-field error
}

Related JSON tools and guides

Frequently asked questions

Does json.Unmarshal reject unknown fields?

Not by default. Use Decoder.DisallowUnknownFields for strict object-field checking.

What is UnmarshalTypeError?

It indicates valid JSON contained a value that could not be assigned to the requested Go destination type.

How do I debug invalid character < in Go JSON?

Inspect the raw HTTP response; the server may have returned HTML instead of JSON.