JSON to Go struct
What is a Json To Go Struct?
In Go, decoding JSON into typed structs gives you compile-time safety and editor autocompletion, but writing struct definitions for a large API response by hand is slow and error-prone. This tool reads a sample JSON payload and generates matching Go structs with json tags, ready to paste into your code.
How to use it
- Paste a representative JSON sample.
- Copy the generated structs.
- Rename the top-level struct and adjust types where the sample was ambiguous.
Example
Input (double quotes in real JSON):
{ 'id': 7, 'user_name': 'asha', 'active': true, 'tags': ['a', 'b'], 'address': { 'city': 'Pune' } }Output:
type AutoGenerated struct {
ID int `json:"id"`
UserName string `json:"user_name"`
Active bool `json:"active"`
Tags []string `json:"tags"`
Address struct {
City string `json:"city"`
} `json:"address"`
}How names and types are mapped
- Field names are converted to exported PascalCase, because
encoding/jsononly fills exported fields. The original key is kept in the tag. - Common initialisms follow Go style:
idbecomesID,urlbecomesURL. - Whole numbers become
int, decimals becomefloat64.
Review before using
- Nulls: a field that is null in the sample has an unknown type; choose a pointer type such as
*string. - Optional fields: add
,omitemptyto tags for fields that may be absent when encoding. - Large IDs: use
int64, orstringif the API sends IDs as strings. - Timestamps: change ISO 8601 strings to
time.Time. - Extract nested anonymous structs into named types if you reuse them.
Frequently Asked Questions
Why are Go struct fields capitalised?
encoding/json can only set exported fields, which must start with an uppercase letter. The json tag keeps the original key name.
How are null values typed?
A null in the sample gives no type information, so use a pointer type such as *string for fields that can be null.
Should I use int or int64?
int is fine on 64-bit systems, but use int64 explicitly for IDs and large numbers to be safe and clear.
How do I handle optional fields?
Add omitempty to the json tag, and use pointers when you need to distinguish missing from zero values.