JSON to Go Struct
Infer Go structs with json tags from a JSON sample.
About JSON to Go Struct
Generate Go structs with json tags from a JSON sample. Paste JSON and gofmt-aligned struct definitions appear as you type, one struct per nested object.
How to use
- Paste JSON, or load a
.jsonfile (up to 5 MB). - Optionally change the root struct name (default
Root). It must start with a letter or underscore and contain only letters, digits and underscores. - The Go code updates as you type. Copy it, or Download it as a
.gofile.
What it does
| JSON | Go |
|---|---|
| string | string |
| integer | int64 |
| other number | float64 |
| boolean | bool |
| null, or mixed types | any |
| array | []T |
| nested object | a named struct, RootAddress |
| null in some items | *T |
| key missing from some items | *T with ,omitempty |
- Field names are PascalCase with the Go initialisms
ID,URL,HTTP,API,JSON,UUIDandIPkept upper case, souser_idbecomesUserID. The original key goes in thejsontag. - Nested structs are listed before the struct that uses them, and the columns of each struct are aligned the way gofmt aligns them.
- A list of objects, including a top-level array, is typed from all its items. Slices and
anyare already nilable, so they do not become pointers.
Example
{ "id": 1, "user_name": "Ada", "tags": ["admin"] }
type Root struct {
ID int64 `json:"id"`
UserName string `json:"user_name"`
Tags []string `json:"tags"`
}
Privacy
Inference runs in the page. No request is made and nothing is stored.
Frequently asked questions
- How do I handle null values in a Go struct?
- Use a pointer type such as *string or *int64. encoding/json sets the pointer to nil for a JSON null and leaves it nil when the key is absent, so you can tell "missing" from the zero value. A nil slice or map already encodes as null without a pointer.
- What does omitempty do?
- The ,omitempty option in a json tag drops the field from the output when it holds its zero value: nil, false, 0, an empty string, or an empty slice or map. It affects marshaling only; decoding ignores it.
- Why are JSON numbers int64 and float64 instead of int?
- int64 is the same size on every platform and holds the full range of integers JSON usually carries, such as IDs and timestamps. Go decodes any JSON number into float64 by default, so float64 is the natural type for values with a fraction.
- Why must struct fields be capitalised?
- encoding/json can only read and write exported fields, and in Go a field is exported when its name starts with an upper-case letter. The json tag maps the exported name back to the original lower-case key.