By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A Go struct is convenient inside your program, but it cannot be stored in a file or sent to another program as it is. JSON is a text format for data that almost every language can read: objects with string keys, arrays, strings, numbers, booleans and null. Go's encoding/json package converts between structs and JSON text in both directions.
Two verbs describe the trip: marshal (struct to JSON bytes) and unmarshal (JSON bytes back into a struct). Penny will use both by the end of this section.
encoding/json only sees exported fields, the ones that start with a capital letter. Without a tag it uses the field name exactly: Cents becomes the key "Cents". A struct tag is a small string after the field type that renames the JSON key. Here is Penny's model:
package main
import "fmt"
// Expense is the Penny data model. The tags name the JSON keys.
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
func main() {
coffee := Expense{ID: 1, Description: "Coffee", Cents: 450, Category: "Food"}
fmt.Printf("%+v\n", coffee)
}The tag is the part between the backticks: json:"cents". It is not Go code in the usual sense; it is metadata that encoding/json reads with reflection. Keep the tag names lowercase and stable, because they become the file format you will have to support later.
json.Marshal returns the JSON bytes and an error. The error is rare for simple structs, but you still check it: some types cannot be encoded, and the habit of checking keeps callers honest.
package main
import (
"encoding/json"
"fmt"
)
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
func main() {
coffee := Expense{ID: 1, Description: "Coffee", Cents: 450, Category: "Food"}
data, err := json.Marshal(coffee)
if err != nil {
fmt.Println("marshal failed:", err)
return
}
fmt.Println(string(data))
}The result is a single line with no spaces. That is the exact text os.WriteFile will save to penny.json, and string(data) is how you print it to look at it.
json.Unmarshal needs the address of the value it should fill, so you pass &decoded. That is a pointer lesson in disguise: an Expense argument would be a copy, and the copy would be thrown away.
package main
import (
"encoding/json"
"fmt"
)
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
func main() {
bus := Expense{ID: 2, Description: "Bus fare", Cents: 300, Category: "Transport"}
data, err := json.MarshalIndent(bus, "", " ")
if err != nil {
fmt.Println("marshal failed:", err)
return
}
fmt.Println(string(data))
var decoded Expense
if err := json.Unmarshal(data, &decoded); err != nil {
fmt.Println("unmarshal failed:", err)
return
}
fmt.Printf("decoded: %+v\n", decoded)
}json.MarshalIndent(value, "", " ") is the pretty-printing version of json.Marshal. The second argument is a prefix for every line and the third is the indentation. Penny saves with MarshalIndent so the file is pleasant to open in an editor; the JSON meaning is identical.
A JSON file written by an older version of your program may have fields your struct no longer has. By default, json.Unmarshal skips unknown keys without complaint, so old files keep loading. That is usually what you want for a data file you control.
package main
import (
"encoding/json"
"fmt"
)
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
func main() {
text := `{"id":3,"description":"Tea","cents":250,"category":"Food","note":"with a friend"}`
var tea Expense
if err := json.Unmarshal([]byte(text), &tea); err != nil {
fmt.Println("unmarshal failed:", err)
return
}
fmt.Printf("%+v\n", tea)
fmt.Println("the extra note field was ignored")
}If you do want strictness, create a decoder with json.NewDecoder(reader) and call decoder.DisallowUnknownFields() before decoding. For a beginner project, the default forgiving behaviour is the right choice.
Add a Paid bool field to Expense with the tag json:"paid", set it to true on the bus fare, marshal it, and look at the output. Then delete the tag and marshal again to see the key become Paid. Finally, try unmarshalling the text {"id":4,"cents":"450"} and read the error message out loud.
Key takeaways
JSON is a text format every language can read; encoding/json converts both ways.
json.Marshal turns a struct into []byte; json.Unmarshal fills a struct from bytes.
json.Unmarshal needs a pointer so it can write into the value.
Struct tags such as json:"cents" set the JSON key names; only exported fields are encoded.
Unknown JSON fields are ignored by default, and MarshalIndent makes files readable.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.