Go JSON Encoding and Decoding Explained

Updated 4 min read
Go JSON featured image: cards showing struct tags, Marshal and Unmarshal

Go JSON handling lets your program turn structs into text and read that text back into structs. In this post, you will learn Marshal, Unmarshal, struct tags and streaming, with the traps that catch beginners. Each idea comes with a short example that you can run yourself.

This data format maps straight onto structs, so first review structs and methods in Go, where you met struct tags. We will also check every error, just like in error handling in Go for beginners.

What Is Go JSON Encoding?

It is a plain text format for data, like {"name":"Asha","age":28}. In fact, almost every web API speaks it. In short, encoding means turning a Go value into that text, and decoding means the reverse.

For example, think of packing a suitcase for a trip. You fold your clothes into a standard shape so they travel well. Then you unpack them at the hotel. Go JSON works the same way with your data, using the encoding/json package.

Struct Tags Control Go JSON

type User struct {
	Name     string   `json:"name"`
	Age      int      `json:"age"`
	Email    string   `json:"email,omitempty"`
	Password string   `json:"-"`
	Skills   []string `json:"skills"`
}

First, the text in backticks tells the package which key name to use. Also, omitempty skips a field when it is empty, and "-" hides it completely. Therefore, it is perfect for secrets like passwords.

Encoding: Struct to Text

u := User{Name: "Asha", Age: 28, Password: "secret", Skills: []string{"Go", "SQL"}}

data, err := json.Marshal(u)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(string(data))
// {"name":"Asha","age":28,"skills":["Go","SQL"]}

json.Marshal returns a byte slice, so convert it with string() to print it. Notice that email is missing because it was empty, and the password never appears. Finally, the diagram below shows both directions.

Go JSON diagram showing a struct turned into JSON with Marshal and back with Unmarshal

Marshal turns a struct into text, and Unmarshal fills a struct from that text, using the tags as key names.

Pretty Printing with MarshalIndent

pretty, _ := json.MarshalIndent(u, "", "  ")
fmt.Println(string(pretty))
// {
//   "name": "Asha",
//   "age": 28,
//   "skills": [
//     "Go",
//     "SQL"
//   ]
// }

In contrast, this version adds line breaks and spaces, which makes logs and config files easy to read. However, it makes the output bigger, so use plain Marshal for Go JSON that travels over the network.

Decoding: Text to Struct

input := `{"name":"Ravi","age":34,"email":"ravi@example.com","skills":["Go"]}`

var r User
if err := json.Unmarshal([]byte(input), &r); err != nil {
	fmt.Println(err)
	return
}
fmt.Println(r.Name, r.Age, r.Email, r.Skills)
// Ravi 34 ravi@example.com [Go]

json.Unmarshal needs a pointer, written as &r, so it can fill the struct. Also, Go simply ignores keys in the input that have no matching field.

Unknown Shapes with map[string]any

var anyData map[string]any
json.Unmarshal([]byte(`{"city":"Pune","pin":411001}`), &anyData)

fmt.Println(anyData["city"], anyData["pin"]) // Pune 411001
fmt.Printf("%T\n", anyData["pin"])           // float64

For instance, when you do not know the shape in advance, decode into a map. However, every number becomes a float64 here, so convert it before you use it as an int.

Streaming Go JSON with Encoder and Decoder

dec := json.NewDecoder(strings.NewReader(`{"name":"Meera","age":25}`))
var m User
dec.Decode(&m)
fmt.Println(m.Name) // Meera

enc := json.NewEncoder(os.Stdout)
enc.Encode(map[string]int{"count": 3}) // {"count":3}

In addition, an Encoder writes straight to a file or network connection, and a Decoder reads from one. For example, web servers use them to read request bodies and write responses.

Go JSON Rules You Must Know

Go typeOutput
string“text”
int, float64number
booltrue or false
slicearray [ ]
struct or mapobject { }
nil pointer or slicenull

Most importantly, only exported fields, the ones starting with a capital letter, appear in the output. So a struct with only lowercase fields encodes as an empty {}.

Common Mistakes with Go JSON

Error you seeWhy it happensHow to fix it
json: cannot unmarshal string into Go struct field User.age of type intThe input has “thirty” for a number.Send a number or change the field type.
invalid character ‘}’ looking for beginning of object key stringThe JSON has a trailing comma.Fix the input text.
json: Unmarshal(non-pointer main.User)The code passed r, not &r.Pass a pointer.
Output is {}All fields are lowercase.Capitalise the field names.

The lowercase field mistake gives no error at all, so it can waste hours. These questions are common in backend interviews, so practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go JSON uses the encoding/json package from the standard library.
  • Marshal turns structs into text, and Unmarshal needs a pointer to fill one.
  • Tags set key names, omitempty skips empty fields, and “-” hides a field.
  • Only exported fields appear, and map numbers become float64.
  • Similarly, use Encoder and Decoder for files and network streams.

What’s Next?

You can now pack and unpack data. Next, we will save it to disk and read it back by working with files.

Coming soon: Go File Handling Explained with Examples