JSON in Go — Marshal, Unmarshal & Struct Tags
Go's encoding/json package is part of the standard library. JSON is marshalled to/from Go structs using struct tags that control field names.
Unmarshal JSON into a struct
Define a struct with json tags matching the JSON keys. Use json.Unmarshal() to parse.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
data := []byte(`{"id":1,"name":"Alice","email":"alice@example.com"}`)
var user User
if err := json.Unmarshal(data, &user); err != nil {
panic(err)
}
fmt.Println(user.Name) // Alice
}Marshal a struct to JSON
Use json.Marshal() to encode a Go struct to JSON bytes, or json.MarshalIndent() for pretty-printing.
user := User{ID: 1, Name: "Alice", Email: "alice@example.com"}
// Compact
b, err := json.Marshal(user)
fmt.Println(string(b))
// Pretty
b, err = json.MarshalIndent(user, "", " ")
fmt.Println(string(b))Omit empty fields
Add omitempty to the json tag to skip zero-value fields during marshalling.
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"` // omitted if empty
}Dynamic JSON with map
Use map[string]interface{} when the JSON structure is not known at compile time.
var result map[string]interface{}
if err := json.Unmarshal(data, &result); err != nil {
panic(err)
}
name := result["name"].(string)
fmt.Println(name)Related Tools
Frequently Asked Questions
How do I parse JSON in Go?▾
Use json.Unmarshal([]byte(jsonString), &target) from the encoding/json package. Define a struct with json struct tags matching the JSON field names.
What are JSON struct tags in Go?▾
Struct tags like `json:"name"` tell the encoding/json package which JSON key maps to which struct field. Use omitempty to skip zero-value fields during marshalling.
How do I marshal a Go struct to JSON?▾
Use json.Marshal(value) for a compact JSON byte slice, or json.MarshalIndent(value, "", " ") for pretty-printed output.
How do I handle unknown JSON keys in Go?▾
Unknown keys are silently ignored by default. To capture them, add a field of type map[string]json.RawMessage and tag it with json:"-".
How do I work with dynamic JSON in Go?▾
Use map[string]interface{} or json.RawMessage for dynamic structures. Use json.Number instead of float64 to preserve numeric precision.
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.