JSON to Go struct
Handy when decoding an API response with encoding/json: it writes a struct per object with the right tags.
Loading the tool…
Processing and privacy: The result is calculated inside your browser and your data is not sent to any server.
How to use it
- Enter json input and root type name.
- The result appears straight away and updates as you edit.
- Copy the result, or copy a link that keeps the same values to share it.
How it is calculated
string, int64, float64 and bool for values, []T for arrays and a separate struct per nested object. Fields are PascalCase with Go initialisms such as ID and URL, and each has a json tag with the original key. A null value makes the field a *T pointer, and a key missing from some items gets omitempty.
Example
Inputs: Root type name = Root. Result: Generated code: type Root struct { ID int64 `json:"id"` Name string `json:"name"` Email string `json:"email"` IsActive bool `json:"is_active"` Balance float64 `json:"balance"` Tags []string `json:"tags"` Address Address `json:"address"` Orders []Order `json:"orders"` } type Address struct { City string `json:"city"` PostalCode string `json:"postal_code"` } type Order struct { OrderID string `json:"order_id"` Total float64 `json:"total"` Coupon *string `json:"coupon"` }; Types generated: 3; Fields: 13.
{
"id": 1024,
"name": "Sara Ahmed",
"email": "sara@example.com",
"is_active": true,
"balance": 1520.75,
"tags": ["vip", "riyadh"],
"address": { "city": "Riyadh", "postal_code": "12211" },
"orders": [
{ "order_id": "A-1", "total": 99.5, "coupon": "EID10" },
{ "order_id": "A-2", "total": 120, "coupon": null }
]
}type Root struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
IsActive bool `json:"is_active"`
Balance float64 `json:"balance"`
Tags []string `json:"tags"`
Address Address `json:"address"`
Orders []Order `json:"orders"`
}
type Address struct {
City string `json:"city"`
PostalCode string `json:"postal_code"`
}
type Order struct {
OrderID string `json:"order_id"`
Total float64 `json:"total"`
Coupon *string `json:"coupon"`
}Limits and caveats
- A key with mixed types becomes any, which needs Go 1.18 or newer.
- Every whole number becomes int64, even small ones.
Questions about this tool
Why are some fields *string or *int64?
A pointer lets you tell a null or missing value apart from a zero value such as "" or 0.
Why ID and not Id?
That is the Go naming convention: initialisms such as ID, URL and API stay fully uppercase.
What does omitempty do?
It drops the field from encoded JSON when the value is empty. It is added to keys that did not appear in every item.
