Skip to content

Instantly share code, notes, and snippets.

@bgbaroo
Last active October 17, 2021 13:34
Show Gist options
  • Save bgbaroo/14f5672bba8946bd8f96515331570641 to your computer and use it in GitHub Desktop.
Save bgbaroo/14f5672bba8946bd8f96515331570641 to your computer and use it in GitHub Desktop.
mapstructure package example with nested struct and tags
package main
import (
"encoding/json"
"fmt"
"github.com/mitchellh/mapstructure"
)
const (
THAILAND = iota + 1
USA
UK
)
type Location struct {
City string
Country int
}
type User struct {
Name string `mapstructure:"username"`
Age int `mapstructure:"age"`
Residence Location `mapstructure:"location, squash"`
Emails []string `mapstructure:"emails"`
Social map[string]interface{} `mapstructure:"social"`
}
func main() {
var input = map[string]interface{}{
"username": "artnoi",
"age": 24,
"emails": []string{"[email protected]", "[email protected]"},
"social": map[string]interface{}{
"twitter": map[string]interface{}{
"username": "artnoi",
"follower": 112,
},
"facebook": map[string]interface{}{
"name": "Prem Phansuriyanon",
"joined": "2012",
},
},
"location": map[string]interface{}{
"City": "Bangkok",
"country": THAILAND,
},
}
var output User
err := mapstructure.Decode(input, &output)
if err != nil {
fmt.Println(err)
}
fmt.Println(output)
b, err := json.Marshal(output)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment