Generate Go structs with JSON tags from sample records
JSON to Go generates a draft struct shape for decoding JSON in Go. It can surface nested records and expected field types quickly.
When should you use it?
- Start structs for an HTTP response.
- Compare a fixture with an existing Go model.
- Identify which JSON keys need field mappings.
Example: infer Go fields from JSON
This abbreviated example shows the inferred name and active fields in Go. The full generated file includes imports and helpers and may change with generator versions; review it before adding it to a project.
{"name":"Alex","active":true}type Root struct {
Name string `json:"name"`
Active bool `json:"active"`
}Preserve the JSON names through struct tags
Go exported fields use names that may differ from the incoming JSON keys. The json tags connect the two. Review those tags before renaming a field, and keep nested structs aligned with nested objects. A sample array is useful when records vary, because one record alone may hide optional properties or several observed value types.
Distinguish zero values from absent fields
An integer field defaults to zero, so its zero value may not tell you whether the JSON contained that field. Pointers or a custom representation may be needed when absence and an explicit zero have different meanings. Review null handling, number ranges, and decoding helpers in the generated output, then test the code with your intended encoding/json usage.
How do I turn JSON into Go structs with json tags?
Paste a representative object and generate Go source. Exported struct fields map to JSON names through tags, so a key’s wire spelling can differ from its Go identifier. Review arrays, nested structs, and null handling before putting the model into a client.
Illustrative Go struct with tags
gotype Root struct {
Name string `json:"name"`
Active bool `json:"active"`
}The generated .go file also contains marshal and unmarshal helpers. A missing field and a zero value can require different handling in application code.
Why should I review numbers in a generated Go struct?
One sample may suggest a narrow or broad numeric shape that does not match every response. Check integer ranges, decimals, and nullable fields against real API data.
What should you check before using the result?
Check exported names, tags, pointers or null handling, number widths, and package conventions before compiling. Unseen optional fields cannot be inferred.
Understand JSON syntaxTechnical reference: quicktype model generation documentation