Skip to content

Instantly share code, notes, and snippets.

@kwmt
Created October 12, 2013 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kwmt/6950666 to your computer and use it in GitHub Desktop.
Save kwmt/6950666 to your computer and use it in GitHub Desktop.
map -> json -> struct
package main
import (
"encoding/json"
"fmt"
)
type example struct {
Name string
Address string
Hobbies []string
}
func main() {
m := make(map[string]interface{})
m["name"] = "go"
m["address"] = "japan"
m["hobbies"] = []string{"watching tv", "listen music"}
fmt.Println(m)
var ex example
MapToStruct(m, &ex)
fmt.Println(ex)
}
func MapToStruct(m map[string]interface{}, val interface{}) error {
tmp, err := json.Marshal(m)
if err != nil {
return err
}
err = json.Unmarshal(tmp, val)
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment