How to Generate Go Structs from JSON
Working with JSON in Go means defining structs with the right json tags. Generating them from a sample gets the tags and naming conventions right automatically. Here's how the output is built.
From JSON to structs
Each JSON object becomes a struct, nested objects become their own structs, and every field carries a json tag with the original key:
{ "id": 1, "user_name": "Ada" }
package main
type Root struct {
ID int `json:"id"`
UserName string `json:"user_name"`
}
The tag is what lets encoding/json marshal and unmarshal the struct back to your exact JSON.
Naming and initialisms
Go exports fields by capitalizing them, and convention says common initialisms stay uppercase. So id becomes ID, url becomes URL, and api_key becomes APIKey — matching what golint/go vet expect, not just Id or Url.
Optional fields: pointers and omitempty
When you convert an array of objects and a key is missing from some elements, the field becomes a pointer with ,omitempty:
Views *int `json:"views,omitempty"`
The pointer lets the field be nil (distinguishing "absent" from "zero"), and omitempty leaves it out of the output when it's empty. Fields with no inferable type fall back to interface{}, and int vs float64 is chosen from whether the numbers are whole.
Related
Generating types for another language? See JSON to TypeScript and JSON to Python.
Try it
Paste a JSON response and get Go structs instantly — everything runs in your browser, nothing uploaded.