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.

Basic Structs

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

  1. Field names are exported — Go requires fields to start with an uppercase letter for JSON marshaling and unmarshaling to work. "name" becomes Name, "id" becomes ID.
  2. JSON tags preserve the original key — The json:"name" tag tells Go's encoding/json package which JSON key maps to which struct field.
  3. Type inference — JSON strings map to string, JSON numbers without decimals map to int (or int64 for large values), numbers with decimals map to float64, and booleans map to bool.

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.

Try It — JSON to Go Struct Converter

Open full tool