go: working with json - marshalling and unmarshaling

2022-09-30

 | 

~2 min read

 | 

263 words

I was trying to understand more about how to actually use the encoding/json package within Golang. Fortunately, Go By Example has a great set of instructions as it relates to [json]](https://gobyexample.com/json).

Still, I wanted to come up with my own example, particularly for unmarshaling. Unmarshaling felt more foreign to me and so I wanted to work through it on my own.

To guide my way, I used the example from The Go Programming Language related to movies as a baseline. Ironically (albeit unsurprisingly), the example I came up with is very similar to the one in the documentation for encoding/json’s Unmarshal.

package main

import (
 "encoding/json"
 "fmt"
)

type movie struct {
 Title   string
 Release int `json:"year"`
}

func main() {
 // First, we'll define the incoming JSON as a byte sequence.
 // We can assume for the moment that this is the response to an API request.
  resp := []byte(`[
    {"title":"Casablanca","year":1942, "color": false},
    {"title":"Cool Hand Luke", "year": 1967, "color": true}
    ]`)

 // Establish a placeholder to put the data we unmarshal.
 var movies []movie

 if err := json.Unmarshal(resp, &movies); err != nil {
  panic(err)
 }

 fmt.Println("unmarshal", movies)
 fmt.Println("access", movies[0].Release, movies[0].Title)
 fmt.Printf("%+v", movies)
}

It’s a simple example, but I learned a few things: particularly how to use the pointer reference as a destination for the unmarshaling.1 In retrospect, this example demonstrates how much further I have to become Golang literate. Ah, the joys of learning!

Here’s the interactive Go Playground

Footnotes

1 I found a great reference sheet on pointers from Joseph Spurrier and republished it here.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!