Basic JSON to Go Struct Conversion
Learn how to convert a simple flat JSON object into a Go struct with exported fields and json tags. Ideal for beginners starting with Go.
Detailed Explanation
Converting a Simple JSON Object to a Go Struct
When you have a flat JSON object with string, number, and boolean fields, converting it to a Go struct is straightforward. Each JSON key becomes an exported Go field with a json struct tag.
Example JSON
{
"id": 42,
"name": "Alice",
"email": "alice@example.com",
"active": true
}
Generated Go Struct
type AutoGenerated struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active"`
}
Key Conversion Rules
- Field names are exported — Go requires fields to start with an uppercase letter for JSON marshaling and unmarshaling to work.
"name"becomesName,"id"becomesID. - JSON tags preserve the original key — The
json:"name"tag tells Go'sencoding/jsonpackage which JSON key maps to which struct field. - Type inference — JSON strings map to
string, JSON numbers without decimals map toint(orint64for large values), numbers with decimals map tofloat64, and booleans map tobool.
Marshaling and Unmarshaling
Once you have the struct, you can decode JSON into it using json.Unmarshal:
var user AutoGenerated
err := json.Unmarshal([]byte(jsonData), &user)
And encode it back with json.Marshal:
data, err := json.Marshal(user)
This is the foundation of all JSON-to-Go conversions. Understanding this pattern is essential before moving on to nested objects, arrays, and more complex structures.
Use Case
When building REST API clients or servers in Go, you frequently receive simple JSON payloads representing a user profile, configuration entry, or status response. Converting these to structs gives you type safety and IDE autocompletion.