

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: JSON Syntax
incomplete
2: Decoding JSON
incomplete
3: JSON Review
incomplete
4: Unmarshal JSON
incomplete
5: Marshal JSON
incomplete
6: XML
incomplete
7: Why Use XML?
incomplete
8: map[string]interface{}
incomplete
This lesson's interactive features are locked, please to keep using them
When we receive JSON data in the body of an HTTP response, it comes as a stream of bytes. As we saw before, we can just convert the bytes to a string... but in Go there's a better way. It's typically best to decode the JSON data into a struct.
Take this example JSON data:
[
{
"id": "001-a",
"title": "Unspaghettify code",
"estimate": 9001
}
]
To decode this JSON into a slice of Issue structs, we need to know the JSON fields and their types. The standard encoding/json package uses tags to map JSON fields to struct fields.
Struct fields must be exported (capitalized) to decode JSON.
type Issue struct {
Id string `json:"id"`
Title string `json:"title"`
Estimate int `json:"estimate"`
}
After receiving the response, we can decode it into a slice of Issues with the "address of" operator &:
// res is a successful `http.Response`
var issues []Issue
decoder := json.NewDecoder(res.Body)
if err := decoder.Decode(&issues); err != nil {
fmt.Println("error decoding response body")
return
}
If no error occurs, we can use the slice of items in our program.
for _, issue := range issues {
fmt.Printf("Issue – id: %v, title: %v, estimate: %v\n", issue.Id, issue.Title, issue.Estimate)
// Issue – id: 001-a, title: Unspaghettify code, estimate: 9001
}
In previous lessons, we've converted response into slices of bytes, and then strings. Now, decode the response data directly into a slice of issues and return that instead.
If any error occurs return a nil slice and the error.