Skip to content

Instantly share code, notes, and snippets.

@jpukg
Forked from kwmt/map-to-struct-with-json.go
Created February 14, 2022 20:59
Show Gist options
  • Save jpukg/ca73c350cc0fd78f670b50cfdc893ee6 to your computer and use it in GitHub Desktop.
Save jpukg/ca73c350cc0fd78f670b50cfdc893ee6 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