How to convert JSON to a Go struct
- Paste a sample JSON document, such as an API response you need to unmarshal.
- Set the root type name.
- Go structs are generated with exported PascalCase field names and
json:"original_key"tags, soencoding/jsonmaps them correctly. - Copy the code into your package and use
json.Unmarshal(data, &v).
Type choices explained
Integers become int64 and decimals float64, based on the values in your sample. Strings and booleans map directly, and arrays become slices such as []string or []Item. Nested objects become their own named struct types, which is easier to work with than anonymous structs.
Fields that are missing from some items get ,omitempty in their tag and, for scalars, a pointer type such as *int64. Fields that can be null also become pointers. That lets your code tell "not present" or "null" apart from a zero value such as 0, "" or false, which is a common source of bugs with Go's JSON decoding. Values with mixed types become any.
Field names follow Go conventions; you may want to adjust initialisms (UserId to UserID) to satisfy linters. Your JSON is processed locally and never uploaded.
FAQ
Why are some fields pointers?
They were optional or null in your sample. A pointer is nil when the field is missing, so you can distinguish it from a real zero value.
Should I use int or int64?
int64 is generated for portability across platforms. Change it to int if you prefer; on 64-bit systems they are the same size.
How do I decode the JSON with this struct?
var r Root; err := json.Unmarshal(body, &r). For HTTP responses, json.NewDecoder(resp.Body).Decode(&r) avoids reading the body into memory first.