JSON to Go Struct: json Tags, omitempty, int vs int64 and Pointers

Last updated: · 8 min read

Before Go code can read an API response, someone has to write the structs that describe it: fields must be exported, each one needs a json tag naming the key it maps to, and every number needs a type that can actually hold it. The JSON to Go Struct Converter writes those definitions from a sample you paste. A sample is not a contract, though. It cannot tell you what type a field has when it only ever appears as null, or whether an ID that looks small today will outgrow 32 bits. This guide explains the naming and typing rules the tool applies, when it adds omitempty or a pointer, and which lines of the generated code deserve a second look. The output shown is the tool's real result, and the conversion runs in your browser.

Formula

Rules:
1. Field names: each key becomes an exported PascalCase name (created_at → CreatedAt). Common initialisms are upper-cased: id → ID, html_url → HTMLURL, api_key → APIKey.
2. Tags: every field gets `json:"key"`, with the key spelled exactly as in the JSON.
3. Numbers are typed by how they are written: no decimal point or exponent and fits in 32 bits → int; fits in 64 bits → int64; written like 4.0, 2.5 or 1e3, or too large for 64 bits → float64.
4. Strings become string and true/false becomes bool. Strings that look like dates stay string.
5. Every nested object becomes its own named type, named after the field and not singularised (repos → Repos, field type []Repos).
6. Array elements are merged into one type. A key missing from some elements gets omitempty; a field that is null in some elements becomes a pointer (*string).
7. Empty arrays, arrays of mixed types and fields that were only ever null become interface{}.
8. A root array is written as type Root []struct { … }.

Input (root type name: user):
{"id":7,"html_url":"https://example.com/u/7","created_at":"2024-05-01T10:00:00Z","followers":3000000000,"rating":4.0,"profile":{"display_name":"Ada","bio":null},"repos":[{"repo_id":1,"private":false},{"repo_id":2,"license":"MIT"}]}

Output:
type User struct {
	ID        int     `json:"id"`
	HTMLURL   string  `json:"html_url"`
	CreatedAt string  `json:"created_at"`
	Followers int64   `json:"followers"`
	Rating    float64 `json:"rating"`
	Profile   Profile `json:"profile"`
	Repos     []Repos `json:"repos"`
}

type Profile struct {
	DisplayName string      `json:"display_name"`
	Bio         interface{} `json:"bio"`
}

type Repos struct {
	RepoID  int    `json:"repo_id"`
	Private bool   `json:"private,omitempty"`
	License string `json:"license,omitempty"`
}

This is type inference, not a formula. The tool parses the JSON, works out a type for every value and merges the objects inside an array field by field. JSON itself (RFC 8259) has a single number type, so the tool goes by spelling: encoding/json refuses to decode a number written as 4.0 into an int field, which is why such values become float64. The initialism rule follows the Go team's code review comments, which ask for acronyms in names to keep a consistent case (URL or url, never Url). Names, types and tags are aligned in columns the way gofmt formats them.

What the inputs mean

JSON
The sample to infer types from. Paste a real response; if you wrap several different records in one array, missing keys (omitempty) and nullable fields (pointers) are detected far more reliably.
Root type name
The name of the outermost type. Root is used when the box is empty. Whatever you type goes through the same naming rules as fields: user → User, api response → APIResponse.

Worked example: Generating structs from a user response

  1. The root type name is user. It is exported, so the first line reads type User struct {.
  2. The id key becomes ID rather than Id, and html_url contains two initialisms: ID int `json:"id"` and HTMLURL string `json:"html_url"`. The tag keeps the key exactly as the JSON spells it.
  3. created_at holds an RFC 3339 timestamp, but the tool does not interpret strings: CreatedAt string `json:"created_at"`. Change the type to time.Time by hand if you want a real time value.
  4. followers is 3000000000, above the 32-bit maximum of 2147483647, so it becomes int64: Followers int64 `json:"followers"`. rating is written 4.0 in the sample, so it becomes float64: Rating float64 `json:"rating"`.
  5. profile is a nested object and gets its own type, Profile. bio is only ever null in this sample, so its type is unknown: Bio interface{} `json:"bio"`. If it is really text, change it to *string.
  6. The two objects in repos are merged into one type. repo_id appears in both; private appears only in the first and license only in the second, so both get omitempty: Private bool `json:"private,omitempty"` and License string `json:"license,omitempty"`.
  7. A nullable field: in [{"id":1,"nick":null},{"id":2,"nick":"ada"}], nick is null in one element and a string in the other. The output starts with type Root []struct { and makes the field a pointer: Nick *string `json:"nick"`.
  8. A limit worth knowing: for {"a,b":1,"count":3.0} the tool writes AB int `json:"a,b"`. encoding/json treats everything after the first comma in a tag as options, so this field is matched to the key a, not a,b. Keys like this need manual handling.

Result: The output consists of three types: User, Profile and Repos. Before using it, give Bio its real type (most likely *string), switch CreatedAt to time.Time and rename Repos to Repo.

🐹 JSON to Go Struct Converter

Free, no sign-up; your data stays in your browser.

Open the calculator →

How to read the result

Treat the generated code as a first draft. omitempty only matters when encoding: Marshal leaves the field out when it holds an empty value (false, 0, a nil pointer, or a string, slice or map of length zero). It has no effect on decoding. One consequence is that Private bool `json:"private,omitempty"` cannot tell false apart from a key that was never sent, and writing the data back out drops every false; use *bool where the difference matters. By default Unmarshal ignores keys that have no matching field and leaves fields the JSON does not mention at their zero value, so a struct on its own validates nothing. In Go, int is 32 or 64 bits depending on the platform; for IDs, counters and timestamps that can grow, int64 is the safer choice. JSON numbers decoded into an interface{} field arrive as float64.

Common mistakes

  • Trusting types generated from a single record. The tool only knows what it saw: with one element in an array, no field is ever marked omitempty or made a pointer.
  • Assuming omitempty affects decoding. The option is for Marshal only; JSON with a missing key decodes fine with or without it, and the field keeps its zero value.
  • Leaving a null-only field as interface{}. Every use then needs a type assertion; find out the real type and write a pointer such as *string or *int.
  • Leaving a nullable field without a pointer. Unmarshal treats null for a non-pointer field as a no-op with no error, so the field stays at its zero value and null can no longer be told apart from 0 or an empty string.
  • Lower-casing the field names. encoding/json only sees exported fields (starting with an upper-case letter); an unexported field silently stays empty. The JSON name comes from the tag, not from the field name.
  • Keeping int for an ID that merely looks small in the sample. The tool picks the type from the sample values; on a 32-bit platform a value above 2147483647 overflows and Unmarshal reports an error.
  • Expecting keys that contain a comma, a double quote or a backslash to work through a tag. According to the encoding/json documentation, the name in a tag is only used if it consists of letters, digits and ASCII punctuation other than those three characters.

Frequently asked questions

What does omitempty do?

When a struct is encoded to JSON, it leaves the field out if it holds an empty value: false, 0, a nil pointer, a nil interface value, or an array, slice, map or string of length zero. The tool adds it to keys that are missing from some objects in an array, so re-encoded JSON stays closer to the original shape.

Should a number be int, int64 or float64?

The tool goes by spelling and size: 7 becomes int, 3000000000 becomes int64, and 4.0 or 1e3 becomes float64. If an array mixes integers and decimals, the element type is float64. Do not change a field written as 4.0 to int even if the values are always whole numbers; encoding/json will not decode that spelling into an integer field.

Why are pointers used for null?

Types such as string and int have no way to represent null in Go. A pointer can be nil, so *string lets you tell a null apart from an empty string. The tool writes a pointer when a field is null in some elements and filled in others; a field that is only ever null becomes interface{}.

Why are fields named ID and URL instead of Id and Url?

Go's code review comments ask for initialisms in names to keep a consistent case: ServeHTTP, appID, URL. That is why the tool turns id into ID and base_url into BaseURL. The JSON name is set by the tag, so renaming a field does not break decoding.

Can I write any instead of interface{}?

Yes. Since Go 1.18, any is a predeclared alias for interface{}; they are the same type. The tool writes interface{} because it also compiles with older Go versions.

Are tag names case-sensitive?

Unmarshal prefers an exact match but also accepts a case-insensitive one. Marshal writes the name exactly as the tag spells it, which is why the tool copies the key into the tag unchanged.

Is my JSON sent to a server?

No. Type inference runs in your browser. It is still good practice to strip access tokens and personal data from a response before pasting it anywhere.

The result is not exact or binding and is for information only; it is not an official document and cannot be used in official procedures. Confirm it with the competent authority or a professional before acting; no liability is accepted for losses arising from its use.

Sources

Choose your cookie preference to continue

Records the site needs to work (theme, language, favourites) stay in your browser.

This site is free and funded by ads.

With your consent, Google Analytics cookies measure visits and Google AdSense cookies are used to show ads; the data is processed on Google servers abroad.

If you reject, the site works just the same.

Cookie Policy · KVKK notice