How to Parse JSON in Go
Go's standard library provides encoding/json. Decode JSON into structs (recommended) or map[string]any with json.Unmarshal, and encode with json.Marshal.
Unmarshal into a struct
Define a struct with json tags and pass a pointer to json.Unmarshal. Unknown fields are ignored.
go
type User struct {
Name string `json:"name"`
Roles []string `json:"roles"`
}
var u User
if err := json.Unmarshal([]byte(text), &u); err != nil {
log.Fatal(err)
}
fmt.Println(u.Name, u.Roles)Decode into a map
When the shape is dynamic, unmarshal into map[string]any.
go
var m map[string]any
if err := json.Unmarshal([]byte(text), &m); err != nil {
log.Fatal(err)
}
fmt.Println(m["name"])Marshal to JSON
json.Marshal returns compact JSON; json.MarshalIndent pretty-prints it.
go
b, _ := json.Marshal(u) // compact
pretty, _ := json.MarshalIndent(u, "", " ") // 2-space indent
fmt.Println(string(pretty))