Start learning free

LESSON 3 OF 173 · BACKEND: HOW THE WEB WORKS

Read a JSON Answer in Go

Practice

Most APIs don't answer with sentences but with JSON, the text format they use to send data. It looks like lists and objects, but it arrives as text: read with io.ReadAll, the body is only bytes of text.

json.NewDecoder(response.Body).Decode(&value) reads that text and fills value with the real Go values it describes: a JSON […] becomes a slice, and a JSON {…} becomes a map. You declare the variable first, and give Decode its address with &. For a weather API whose body is {"city": "Paris", "temp": 18}:

var weather map[string]any
json.NewDecoder(response.Body).Decode(&weather)
fmt.Println(weather["city"], weather["temp"])   // Paris 18

The supplier's price list is at the path /prices. Its body is a list of products, and each product is an object with an "id", a "name" and a "price": in Go, a []map[string]any. Your program must print:

5 products
map[id:1 name:Mug price:5]
Mug costs 5
Notebook costs 3
Lamp costs 14
Pen costs 1
Plant costs 6

Your task: request /prices, decode the body into products, a slice of maps, print how many products there are and the first one, then loop over the slice with range and print each product's name and price.


Assignment
Follow the Coding Tutorial to read the supplier's price list as JSON and print every product's name and price.


Hint
products is a slice of maps: len counts its items, products[0] is the first map, and inside the loop each product is read by key, with the key's name in quotes inside square brackets. range gives the index first: skip it with _.


STEP 1 OF 6
    Ctrl + Enter to check

    Web Json Answer in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free