« Back to Index

Convert a Map to a Struct

View original Gist on GitHub

Tags: #go #serialization

Golang Map to Struct.md

Going from a map (such as map[string]interface) to a struct is possible, but you need to run through the following steps:

Note: an example of why you would do this is when getting a JSON API response (in that scenario you’d also have to first json.Unmarshal the JSON data into a map, so that’s yet another step!)

It would be nice if the steps could just be:

This is where the mitchellh/mapstructure package comes in. It utilizes reflection to support this behaviour.

package main

import (
	"fmt"

	"github.com/mitchellh/mapstructure"
)

type Data struct {
	Foo int
	Bar string
	Baz bool `mapstructure:"beep"` // demonstrates how to translate a map key to a different struct field
}

func main() {
	m := map[string]interface{}{
		"foo":  5,
		"bar":  "nice",
		"beep": true, // this will be stored in a field called 'Baz'
	}
	fmt.Printf("%+v\n", m) // map[bar:nice boolean:true foo:5]

	var result Data
	mapstructure.Decode(m, &result)
	fmt.Printf("%+v\n", result) // {Foo:5 Bar:nice Baz:true}
}