Xerobit
Data & Format

JSON to Go Struct: Tags, Nulls and Unmarshal Errors

Write a Go struct from a JSON sample and unmarshal it. Tested handling of null, omitempty, big int64, time.Time and the exact 'cannot unmarshal' error messages with fixes.

MA Mian Ali Khalid Updated Nov 2, 2026 8 min read
Free tool
JSON Formatter
Format, validate, and beautify JSON online. 100% client-side, your data never leaves your browser.
Open tool →
On this page ⌄
  1. The sample and the struct
  2. The errors, and what causes each
  3. null, missing and omitempty
  4. Numbers: int64, float64 and json.Number
  5. Dynamic keys, mixed types and strict decoding
  6. Frequently asked questions
  7. Tested

Turning a JSON payload into a Go struct is mechanical, which is why generators exist. What decides whether the struct works in production is the part generators cannot see: which fields can be null, which numbers overflow, and what encoding/json does when the payload disagrees with your types. This guide writes the struct for one sample, then feeds it bad input and records the exact errors.

The struct below is written by hand from the sample following the mapping rules in the next section. Xerobit does not have a Go generator at the time of writing (it has JSON to C#, JSON to TypeScript and others), so if you use any generator, run its output through the same checks.

The sample and the struct

{
  "repoName": "xerobit-dev",
  "stars": 142,
  "isPrivate": false,
  "owner": { "login": "MAK", "type": "User" },
  "topics": ["astro", "seo", "tools"],
  "homepage": null,
  "updatedAt": "2026-05-12T14:30:00Z"
}
type Owner struct {
	Login string `json:"login"`
	Type  string `json:"type"`
}

type Repo struct {
	RepoName  string    `json:"repoName"`
	Stars     int       `json:"stars"`
	IsPrivate bool      `json:"isPrivate"`
	Owner     Owner     `json:"owner"`
	Topics    []string  `json:"topics"`
	Homepage  *string   `json:"homepage"`
	UpdatedAt time.Time `json:"updatedAt"`
}

The rules behind it: field names must be exported (capitalized) or encoding/json cannot set them; the tag carries the original key; nested objects become their own struct; arrays become slices; a null in the sample becomes a pointer; a timestamp string becomes time.Time, which parses RFC 3339 on its own.

var r Repo
if err := json.Unmarshal([]byte(data), &r); err != nil { panic(err) }
fmt.Printf("%+v\n", r)
// {RepoName:xerobit-dev Stars:142 IsPrivate:false Owner:{Login:MAK Type:User}
//  Topics:[astro seo tools] Homepage:<nil> UpdatedAt:2026-05-12 14:30:00 +0000 UTC}

Before generating anything from a real response, check that the response is valid JSON in the JSON Formatter or the JSON Validator. A generator working on a payload with a trailing comma either fails or guesses.

The errors, and what causes each

Each line is the exact err.Error() from json.Unmarshal into the structs above (Go 1.23.4). Go has changed this wording across releases, so a message from an older toolchain may look slightly different.

InputTargetError
{"stars":"142"}Repojson: cannot unmarshal string into Go struct field Repo.stars of type int
{"stars":2.5}Repojson: cannot unmarshal number 2.5 into Go struct field Repo.stars of type int
{"stars":99999999999999999999}Repojson: cannot unmarshal number 99999999999999999999 into Go struct field Repo.stars of type int
{"repoName":"x"}[]Repojson: cannot unmarshal object into Go value of type []main.Repo
[{"repoName":"x"}]Repojson: cannot unmarshal array into Go value of type main.Repo
{"owner":{"login":5}}Repojson: cannot unmarshal number into Go struct field Owner.owner.login of type string
{"topics":["a",2]}Repojson: cannot unmarshal number into Go struct field Repo.topics of type string
{"updatedAt":"yesterday"}Repoparsing time "yesterday" as "2006-01-02T15:04:05Z07:00": cannot parse "yesterday" as "2006"
<!DOCTYPE html><html>Repoinvalid character '<' looking for beginning of value
{"stars":1Repounexpected end of JSON input
{"stars":1,}Repoinvalid character '}' looking for beginning of object key string
{'stars':1}Repoinvalid character '\'' looking for beginning of object key string
empty stringRepounexpected end of JSON input

Fixes, by pattern:

  • cannot unmarshal string into Go struct field ... of type int: the API sends numbers as strings ("142"). Either type the field as string and convert, or add the ,string tag option (json:"stars,string"), which makes encoding/json read the quoted number.
  • cannot unmarshal number 2.5 ... of type int: your sample had whole numbers. Use float64.
  • cannot unmarshal object into Go value of type []main.Repo: the endpoint returned {...} and you decoded into a slice. The reverse gives "array into Go value of type main.Repo". Wrappers such as {"data":[...]} are the usual cause: decode into a struct with a Data []Repo field.
  • A very large number into int: use int64 or uint64, or json.Number.
  • invalid character '<' looking for beginning of value: the body is HTML, almost always an error page. Print the first 200 bytes of the response and check the status code before decoding.
  • unexpected end of JSON input: the body is empty or cut off. Check the HTTP status and whether you read the body fully.
  • The parsing time error: the string is not RFC 3339. Use a string field and parse with the layout you need, or write a custom UnmarshalJSON.

One behavior is easy to miss (it was tested twice): a type mismatch does not abort the whole decode. Unmarshal keeps going, fills in what it can, and returns the first such error at the end, so a half-filled struct plus a non-nil error is possible. Always check err before using the result.

null, missing and omitempty

JSON null and a missing key look the same to a plain field. Both leave the zero value, and a null into a non-pointer string is silently skipped:

Unmarshal(`{"repoName":null}`, &Repo{RepoName: "keep"})
// ok, RepoName is still "keep"

A pointer is how you tell "absent or null" apart from "zero": with Homepage *string, the sample's null leaves Homepage == nil. omitempty only affects marshalling, and it treats a pointer and a value differently:

type Opt struct {
	A int     `json:"a,omitempty"`
	B *int    `json:"b,omitempty"`
	D *string `json:"d"`
}
zero := 0
json.Marshal(Opt{A: 0, B: &zero})
// {"b":0,"d":null}

A (a plain zero int) was dropped, B (a pointer to zero) was kept as 0, and D (no omitempty, nil pointer) was written as null. So use *int with omitempty when 0 is a legitimate value you must send. Decoding {"b":0} into the same struct gave a non-nil B pointing at 0, while a missing b left it nil.

If you read from a database, sql.NullString is the wrong type for JSON: it marshalled as {"N":{"String":"x","Valid":true}}, not as a string. Use *string for the JSON layer.

Numbers: int64, float64 and json.Number

Decoding into map[string]any turns every number into float64, and that loses large IDs:

big := `{"id":9007199254740993}`
var m map[string]any
json.Unmarshal([]byte(big), &m)      // m["id"] = 9.007199254740992e+15 (float64), off by one
var st struct{ ID int64 `json:"id"` }
json.Unmarshal([]byte(big), &st)     // st.ID = 9007199254740993, exact

If you must decode into any, call dec.UseNumber() on a json.Decoder: the value then arrives as json.Number and printed 9007199254740993. A typed int64 field is simpler.

Dynamic keys, mixed types and strict decoding

  • Unknown keys as map keys: map[string]Owner decoded {"a":{...},"b":{...}} into two entries, m["b"].Login == "u2".
  • Deferred parsing: a json.RawMessage field keeps a subtree as bytes until you know its type. Decoding {"type":"owner","data":{"login":"z","type":"Org"}} into Env{Type string; Data json.RawMessage} and then unmarshalling Data into Owner gave {Login:z Type:Org}.
  • A field that is sometimes a number and sometimes a string: implement UnmarshalJSON on a small type. A version that strips quotes read {"id":42} as 42 and {"id":"abc"} as abc. Add real validation for production use.
  • Matching is case-insensitive: {"REPONAME":"Upper","Stars":3} filled RepoName and Stars even though the tags are repoName and stars. A typo in a tag's case therefore may not show up in tests.
  • Strict mode: dec.DisallowUnknownFields() turned {"stars":1,"extra":true} into json: unknown field "extra". Use it for config files, not for third-party APIs that add fields.

Frequently asked questions

How do I convert JSON to a Go struct online? Use any generator, then verify with the table above: check pointer fields for nulls, change numeric IDs to int64, and confirm timestamps are RFC 3339.

What does omitempty do in a Go struct tag? It omits the field when marshalling if it is the zero value (0, "", false, nil pointer, empty slice or map). It does nothing when unmarshalling.

How do I handle nested JSON in Go? One struct per object, referenced by field type, as Owner is in Repo. For an object you will not model, use map[string]any or json.RawMessage.

Why does json.Unmarshal leave my field empty with no error? Unexported field name, a tag that names a different key, or a null in the payload. Fields with a lowercase first letter are never filled.

Tested

2026-11-02: Go 1.23.4 (windows/amd64). All structs, outputs and error messages above come from one program run with go run, using only the standard library (encoding/json, time, database/sql). The "Tested" errors reflect Go 1.23 wording.

Keep reading

Related tools

Written by Mian Ali Khalid. More guides in Data & Format.