How to Parse JSON in Go

← All guides

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))

Frequently Asked Questions

Struct fields must be exported (capitalized) and usually need json tags to map lowercase JSON keys. Unexported fields are skipped.

Use the JSON to Go tool — paste a sample JSON document and get ready-to-use structs with correct json tags.

By default extra JSON fields are ignored. Use json.Decoder with DisallowUnknownFields() if you want to reject them.

Related Tools