JSON to Go Struct Converter
Turn JSON into Go structs with json tags, plus Unmarshal and Marshal helpers for encoding/json.
Generate Go structs with json tags from JSON
Go needs a struct for every JSON object you want to decode, and every field needs a json tag when the key does not match the Go name. This converter writes those structs for you: snake_case keys such as allowed_origins become exported fields such as AllowedOrigins with the matching json tag, nested objects become separate struct types, whole numbers become int64 and decimals float64. It also adds an Unmarshal function and a Marshal method built on the standard encoding/json package, so there are no third-party dependencies.
How to use
- Paste a JSON sample, such as a config file or an API response.
- Enter the root struct name, for example ServerConfig.
- Copy the code into a .go file, change package main to your own package name, and decode with json.Unmarshal or the generated Unmarshal function.
Frequently asked questions
- Why are numbers generated as int64 instead of int?
- JSON has no size limit for integers, so int64 is the safe choice on every platform. You can change a field to int after copying if you know the value range.
- How do I add omitempty to the json tags?
- The generator writes plain tags that match the keys in your sample. Add ,omitempty by hand to fields that should be left out when empty during Marshal; decoding works the same either way.
- How are nullable or missing fields handled?
- If the sample shows a field as null, or missing in some array items, it is generated as a pointer type such as *string, so you can tell an absent value from an empty one.
Example: JSON to Go
Input JSON
{
"host": "0.0.0.0",
"port": 8080,
"debug": false,
"allowed_origins": ["https://jsonkit.org"],
"database": { "dsn": "postgres://localhost/app", "max_conns": 20 }
}Generated Go (ServerConfig)
// Code generated from JSON Schema using quicktype. DO NOT EDIT.
// To parse and unparse this JSON data, add this code to your project and do:
//
// serverConfig, err := UnmarshalServerConfig(bytes)
// bytes, err = serverConfig.Marshal()
package main
import "encoding/json"
func UnmarshalServerConfig(data []byte) (ServerConfig, error) {
var r ServerConfig
err := json.Unmarshal(data, &r)
return r, err
}
func (r *ServerConfig) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type ServerConfig struct {
Host string `json:"host"`
Port int64 `json:"port"`
Debug bool `json:"debug"`
AllowedOrigins []string `json:"allowed_origins"`
Database Database `json:"database"`
}
type Database struct {
DSN string `json:"dsn"`
MaxConns int64 `json:"max_conns"`
}