Turning Go values into JSON and back

JSON is a text format for data. Web services and config files use it, and programs use it to send data to each other. A JSON object looks like this:

{"title":"Go Basics","pages":120,"price":9.5}

It has keys in double quotes, a colon, and a value. Values can be text, numbers, true or false, lists in [ ] and other objects. Go's standard package encoding/json turns Go structs into JSON and back.

From a struct to JSON

Encoding (also called marshaling) means turning a Go value into JSON text. json.Marshal does it:

package main

import (
	"encoding/json"
	"fmt"
)

type Book struct {
	Title string   `json:"title"`
	Pages int      `json:"pages"`
	Price float64  `json:"price"`
	Tags  []string `json:"tags"`
}

func main() {
	b := Book{
		Title: "Go Basics",
		Pages: 120,
		Price: 9.5,
		Tags:  []string{"go", "intro"},
	}
	data, err := json.Marshal(b)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(string(data))
}

Output:

{"title":"Go Basics","pages":120,"price":9.5,"tags":["go","intro"]}

The import path is encoding/json, but in the code you write only the last part, json.

The text in backticks after each field, like `json:"title"`, is a struct tag. It tells the json package which key to use. JSON keys are usually lower case, but Go fields that the package can see must start with a capital letter. The tag connects the two. A field with no tag uses its Go name as the key, like "Title". The slice became a JSON list.

json.Marshal returns a []byte, a slice of bytes, because JSON is usually written to a file or sent over a network. string(data) turns the bytes into a string so you can print it.

Lowercase fields are left out

The json package can only see exported fields, the ones whose names start with a capital letter. A lowercase field is skipped, with no error:

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name     string `json:"name"`
	password string `json:"password"`
}

func main() {
	u := User{Name: "Alice", password: "x7k"}
	data, err := json.Marshal(u)
	fmt.Println(string(data), err)
}

Output:

{"name":"Alice"} <nil>

The password is missing from the output and err is nil. This is a common surprise. If a field is missing from your JSON, check its first letter.

Pretty output

json.MarshalIndent adds new lines and spaces so people can read the JSON more easily. The last two arguments are the text to put at the start of each line (none here) and the indent for each level (two spaces). This example encodes a map. A map becomes a JSON object, with its keys in sorted order:

scores := map[string]int{"bob": 72, "alice": 90}
data, _ := json.MarshalIndent(scores, "", "  ")
fmt.Println(string(data))

Output:

{
  "alice": 90,
  "bob": 72
}

From JSON to a struct

Decoding (unmarshaling) goes the other way. json.Unmarshal takes the JSON as a []byte and a pointer to the value it should fill:

package main

import (
	"encoding/json"
	"fmt"
)

type Book struct {
	Title string `json:"title"`
	Pages int    `json:"pages"`
}

func main() {
	text := `{"title":"Maps","pages":80,"year":2024}`
	var b Book
	err := json.Unmarshal([]byte(text), &b)
	fmt.Printf("%+v %v\n", b, err)

	bad := `{"title":"Maps","pages":"eighty"}`
	err = json.Unmarshal([]byte(bad), &b)
	fmt.Println(err)
}

Output:

{Title:Maps Pages:80} <nil>
json: cannot unmarshal string into Go struct field Book.pages of type int

A string in backticks, like text, is a raw string: the double quotes inside it need no backslash. []byte(text) turns the string into bytes. &b is needed so Unmarshal can change b, just like fmt.Scan.

%+v prints a struct with its field names. The key year has no field in Book, so it was ignored. The second JSON has text where a number should be, so Unmarshal returned an error. Always check that error. JSON often comes from outside your program, and it can be wrong.

In the exercise, decode an order from JSON with json.Unmarshal, add a delivery fee, and encode it again with json.Marshal.