I need to convert a map[string]interface{}
whose keys are json tag names to struct
type MyStruct struct {
Id string `json:"id"`
Name string `json:"name"`
UserId string `json:"user_id"`
CreatedAt int64 `json:"created_at"`
}
The map[string]interface{}
has keys id
, name
, user_id
, created_at
. I need to convert this into struct
.
If I understood well, you have a map and want to fill struct by. If it's first change it to jsonString and then Unmarshal it to struct
package main
import (
"encoding/json"
"fmt"
)
type MyStruct struct {
Id string `json:"id"`
Name string `json:"name"`
UserId string `json:"user_id"`
CreatedAt int64 `json:"created_at"`
}
func main() {
m := make(map[string]interface{})
m["id"] = "2"
m["name"] = "jack"
m["user_id"] = "123"
m["created_at"] = 5
fmt.Println(m)
// convert map to json
jsonString, _ := json.Marshal(m)
fmt.Println(string(jsonString))
// convert json to struct
s := MyStruct{}
json.Unmarshal(jsonString, &s)
fmt.Println(s)
}
You can use https://github.com/mitchellh/mapstructure for this. By default, it looks for the tag mapstructure
; so, it's important to specify TagName
as json
if you want to use json tags.
package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
)
type MyStruct struct {
Id string `json:"id"`
Name string `json:"name"`
UserId string `json:"user_id"`
CreatedAt int64 `json:"created_at"`
}
func main() {
input := map[string]interface{} {
"id": "1",
"name": "Hello",
"user_id": "123",
"created_at": 123,
}
var output MyStruct
cfg := &mapstructure.DecoderConfig{
Metadata: nil,
Result: &output,
TagName: "json",
}
decoder, _ := mapstructure.NewDecoder(cfg)
decoder.Decode(input)
fmt.Printf("%#v
", output)
// main.MyStruct{Id:"1", Name:"Hello", UserId:"123", CreatedAt:123}
}