Golang in sixty seconds — consuming JSON

Photo of JSON business card, showing logo and text “JSON Data Interchange Format”
Image by superfluity (license)

My previous article spoke about Marshalling JSON into a Go type. Let's look at how you can do the opposite — Unmarshalling

type person struct {
  Name string `json:"First name"`
  age  int
}
func main() {
  j := `{"First name":"Mike","age":25}`
  p := person{}
  json.Unmarshal([]byte(j), &p)
  fmt.Println(p) // {Mike 0}
}

To unmarshal the JSON, you first need to create an instance of a type ( pin the example above), then pass the pointer &p to the Unmarshal function along with the JSON data as a byte slice. Similar to the json.Marshal function, it will only use exported fields, so our output has the nil value for an int (0).

You can use an empty interface in order to marshal or unmarshal data without specifically knowing what it will look like. I've found this useful for services which pass metadata around without actually making use of it.

type person struct {
  Name     string `json:"First name"`
  age      int
  Metadata map[string]interface{} `json:"metadata"`
}
func main() {
  j := `{"First name":"Mike","age":25, "metadata": {"some":"stuff","things":[1,2,3]}}`
  p := person{}
  json.Unmarshal([]byte(j), &p)
  fmt.Println(p) // {Mike 0 map[some:stuff things:[1 2 3]]}
}

You can see this example here.

Richard Bell

Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.