JSON to Go
Generate Go structs with json tags from a JSON sample: int64 and float64 detection, pointers and omitempty for optional fields, and Go-style initialisms.
Local workspace
Named projects in IndexedDB · Local only — never synced to our servers. Worksp…
Batch workspace
Format multiple files locally in one run.
Writing Go structs for a JSON API by hand means deciding, field by field, between int64 and float64, value and pointer, and what to put in each tag. This generator decides from the data: it merges every item of an array, uses float64 as soon as one sample is fractional, makes fields pointers when they can be missing or null, adds omitempty to optional fields, and names types with Go initialisms such as UserID. Fields with mixed types become any, and identical nested objects share one struct.
Common errors and fixes
json: cannot unmarshal string into Go struct field
The payload has a string where the struct expects a number, or the reverse. Generate from a sample with the real types, or use json.Number for numbers that arrive as strings.
json: cannot unmarshal number 18.25 into Go struct field Order.total of type int64
Real data has a fractional value the sample didn't. Add a fractional sample so the field is generated as float64.
json: cannot unmarshal array into Go value of type main.Root
The JSON root is an array. Decode into the generated slice type, such as RootList, instead of Root.
json: unknown field
Decoder.DisallowUnknownFields rejects keys the struct doesn't declare. Add the field, or generate from a more complete sample.
Options
| Option | Description |
|---|---|
| Root name | Name of the top-level struct. Nested structs are named after their JSON keys. |
| omitempty on optional fields | Adds ,omitempty to the json tag of fields missing from some samples, so encoding skips them when they're nil. |
FAQ
Why are some fields pointers like *string?
The key is missing from some samples or is null. A pointer lets your code tell an absent or null value apart from the zero value, such as an empty string or 0.
How does it choose between int64 and float64?
Whole numbers in every sample become int64. If any sample has a fractional part, the field becomes float64. JSON numbers carry no type, so include a fractional sample for fields that can hold decimals.
What does omitempty do in a json tag?
It makes json.Marshal skip the field when it's nil or a zero value. The generator adds it to optional fields so re-encoding doesn't add keys the original payload never had. It has no effect on Unmarshal.
Why is a field typed as any?
The samples had mixed types at that key, such as a number and a string, or only null. Keep any, use json.RawMessage to decode it later, or write a custom UnmarshalJSON.
Why are names like ID and URL in capitals?
Go's code review guidelines keep initialisms in one case, so user_id becomes UserID. Struct tags still carry the original JSON key, so decoding isn't affected.