A SkilledHat solution · Updated 5 December 2026

Go JSON: Structs, Marshal and Unmarshal

Convert JSON to Go structs here, then decode and encode API responses with encoding/json. We show tags, nulls, dates and common errors with runnable examples.

Options and compatibility

Compatibility mode sends JSON to our server and provides a ZIP with sample usage.

Modern conversion stays in your browser. Privacy policy · Open in the Workbench

From JSON to a working Go program

Paste a representative API response into the converter. Modern output stays in your browser with copy and download; compatibility mode sends JSON to our server and provides a ZIP. A sample is not a complete API schema: empty arrays cannot reveal element types, and absent fields cannot reveal names or types.

Every code block is a standalone main.go. Save one block at a time and run go run main.go. Only the standard library is needed, with Go 1.22 or later. Generated models use package models: when combining them with a main.go, keep one package declaration and consolidate imports.

Struct tags, nested objects and json.Unmarshal

Only exported fields participate in encoding/json. A json tag preserves display_name while the Go identifier remains DisplayName. Pass a pointer to Unmarshal so it can fill the destination. Marshal returns JSON bytes; always check both errors.

package main
import ("encoding/json"; "fmt")
type Address struct { City string `json:"city"` }
type User struct { ID int64 `json:"id"`; DisplayName string `json:"display_name"`; Tags []string `json:"tags"`; Address Address `json:"address"` }
func main() {
 input := []byte(`{"id":7,"display_name":"Ada","tags":["go"],"address":{"city":"Oslo"}}`)
 var user User
 if err := json.Unmarshal(input, &user); err != nil { panic(err) }
 if user.DisplayName != "Ada" || user.Address.City != "Oslo" { panic("wrong model") }
 output, err := json.Marshal(user)
 if err != nil { panic(err) }
 fmt.Println(string(output))
}

Top-level arrays and portable numbers

Decode a top-level array into []User rather than User. Nested arrays become slices of slices. Use int64 for signed 64-bit IDs, not architecture-sized int. For exact decimal money, choose a deliberate decimal representation rather than assuming float64 arithmetic is exact.

package main
import ("encoding/json"; "fmt")
type User struct { ID int64 `json:"id"` }
func main() {
 var users []User
 if err := json.Unmarshal([]byte(`[{"id":9007199254740993}]`), &users); err != nil { panic(err) }
 if len(users) != 1 || users[0].ID != 9007199254740993 { panic("lost precision") }
 data, err := json.Marshal(users)
 if err != nil { panic(err) }
 fmt.Println(string(data))
}

Missing, null and zero are different

Pointers versus zero values

A fresh *int distinguishes a supplied zero from absent or null, but not absent from explicit null. Fresh non-pointer numeric fields stay zero for missing keys; null leaves their current value unchanged. Reusing a destination can retain old values for missing keys: decode independent responses into fresh values.

package main
import ("encoding/json"; "fmt")
type Patch struct { Count *int `json:"count"` }
func main() {
 for _, input := range []string{`{}`, `{"count":null}`, `{"count":0}`} {
  var patch Patch
  if err := json.Unmarshal([]byte(input), &patch); err != nil { panic(err) }
  if patch.Count == nil { fmt.Println("absent or null") } else { fmt.Println(*patch.Count) }
 }
}

omitempty controls encoding, not validation

omitempty skips false, numeric zero, nil pointers and zero-length strings, slices or maps. A non-nil pointer to zero is included. Without omitempty, a nil slice encodes as null and an allocated empty slice as []. omitempty does not reject missing fields during Unmarshal: validate required fields after decoding.

package main
import ("encoding/json"; "fmt")
type Response struct { Count int `json:"count,omitempty"`; Enabled *bool `json:"enabled,omitempty"`; Items []string `json:"items"` }
func main() {
 enabled := false
 data, err := json.Marshal(Response{Enabled:&enabled, Items:[]string{}})
 if err != nil { panic(err) }
 fmt.Println(string(data)) // {"enabled":false,"items":[]}
}

Embedded structs and nesting

Anonymous exported structs normally promote their fields into the containing JSON object. An explicit tag names the embedded value instead. Prefer an ordinary named field for an actual nested object. Avoid overlapping promoted names: conflicts can cause fields to be ignored without an error.

package main
import ("encoding/json"; "fmt")
type Meta struct { ID int `json:"id"` }
type Flat struct { Meta; Name string `json:"name"` }
type Nested struct { Meta `json:"meta"`; Name string `json:"name"` }
func main() {
 for _, value := range []any{Flat{Meta{7},"Ada"}, Nested{Meta{7},"Ada"}} {
  data, err := json.Marshal(value)
  if err != nil { panic(err) }
  fmt.Println(string(data))
 }
}

Dates and delayed decoding

time.Time expects RFC 3339

JSON has no date type. time.Time decodes quoted RFC 3339 timestamps, not Unix numbers or arbitrary date-only strings. Use a string or custom UnmarshalJSON for a different contract. A struct-valued time.Time is not omitted by omitempty in encoding/json v1; use *time.Time with omitempty for an absent timestamp.

package main
import ("encoding/json"; "fmt"; "time")
type Event struct { CreatedAt time.Time `json:"created_at"`; DeletedAt *time.Time `json:"deleted_at,omitempty"` }
func main() {
 var event Event
 if err := json.Unmarshal([]byte(`{"created_at":"2026-12-05T05:40:00Z"}`), &event); err != nil { panic(err) }
 fmt.Println(event.CreatedAt.UTC().Format(time.RFC3339))
 output, err := json.Marshal(event)
 if err != nil { panic(err) }
 fmt.Println(string(output))
}

json.RawMessage for polymorphic payloads and presence

RawMessage keeps a JSON value for later decoding without converting its numbers to float64. Decode an envelope discriminator first, then choose a payload type. A map of RawMessage distinguishes absent keys from explicit null. Keep this representation when large integers must survive unchanged.

package main
import ("encoding/json"; "fmt")
type Envelope struct { Kind string `json:"kind"`; Data json.RawMessage `json:"data"` }
func main() {
 var event Envelope
 input := []byte(`{"kind":"user","data":{"id":9007199254740993},"nickname":null}`)
 if err := json.Unmarshal(input, &event); err != nil { panic(err) }
 switch event.Kind {
 case "user":
  var user struct { ID int64 `json:"id"` }
  if err := json.Unmarshal(event.Data, &user); err != nil { panic(err) }
  fmt.Println(user.ID)
 default: panic("unsupported event kind")
 }
 var fields map[string]json.RawMessage
 if err := json.Unmarshal(input, &fields); err != nil { panic(err) }
 value, present := fields["nickname"]
 fmt.Println(present, string(value)) // true null
}

Common Go JSON errors and fixes

Wrong types, invalid JSON and pointer errors

UnmarshalTypeError means a value disagrees with its destination type: a quoted "7" is a string, not a number. SyntaxError means malformed JSON. InvalidUnmarshalError means the destination is not a usable pointer. The destination can be partially filled on an error; do not use it as a valid response.

package main
import ("encoding/json"; "fmt"; "errors")
func main() {
 var user struct { ID int `json:"id"` }
 for _, input := range []string{`{"id":"7"}`, `{"id":`} {
  err := json.Unmarshal([]byte(input), &user)
  var mismatch *json.UnmarshalTypeError
  var syntax *json.SyntaxError
  switch {
  case errors.As(err, &mismatch): fmt.Println("type mismatch:", mismatch.Field)
  case errors.As(err, &syntax): fmt.Println("invalid JSON at byte", syntax.Offset)
  default: panic("expected decoding failure")
  }
 }
 var destination *struct { ID int `json:"id"` }
 err := json.Unmarshal([]byte(`{"id":7}`), destination)
 var invalid *json.InvalidUnmarshalError
 if !errors.As(err, &invalid) { panic("expected pointer error") }
 fmt.Println("pass a non-nil pointer")
}

Strict decoding: unknown keys and trailing JSON

Unmarshal ignores unknown object keys by default. Decoder.DisallowUnknownFields rejects them for a strict contract. A single Decoder.Decode reads one JSON value: require EOF after the first to reject trailing data. Decoder.UseNumber preserves numeric text in interface values, which otherwise use float64; it does not validate business rules.

package main
import ("encoding/json"; "fmt"; "strings"; "io")
func decode(input string) error {
 decoder := json.NewDecoder(strings.NewReader(input))
 decoder.DisallowUnknownFields()
 var user struct { ID int `json:"id"` }
 if err := decoder.Decode(&user); err != nil { return err }
 var extra any
 if err := decoder.Decode(&extra); err != io.EOF {
  if err != nil { return err }
  return fmt.Errorf("expected one JSON value")
 }
 return nil
}
func main() {
 if err := decode(`{"id":7}`); err != nil { panic(err) }
 for _, input := range []string{`{"id":7,"typo":true}`, `{"id":7} {}`} {
  if err := decode(input); err == nil { panic("expected rejection") } else { fmt.Println(err) }
 }
}

Why is my Go field missing from JSON?

Check that the field is exported, its tag has the correct wire name and it is not tagged with a lone dash, which ignores it. An omitempty field can disappear because its value is empty. A conflicting embedded field can disappear too. The converter uses RawMessage-backed maps for keys Go struct tags cannot represent faithfully, rather than silently changing the JSON contract.

Can the generator replace an API schema?

No. Generate from representative responses, then review required fields, nullability, number limits and union variants against your API contract. Keep fixtures for the payloads your client relies on and check decoding errors before using the result.

Our converter provides repeatable local output, copy and download without a prompt or account. Convert another response · Open Go in the Workbench · Go encoding/json reference