Last active
October 17, 2021 13:34
-
-
Save bgbaroo/14f5672bba8946bd8f96515331570641 to your computer and use it in GitHub Desktop.
mapstructure package example with nested struct and tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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