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
.
There are two steps: Convert interface to JSON Byte. Convert JSON Byte to struct.
The difference between those two types is just what it seems: interface{} is the "any" type, since all types implement the interface with no functions. map[string]interface{} is a map whose keys are strings and values are any type.
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)
}
Update 2021-08-23
while I see ,this post is useful. I posted a complete sample on my gist, please check it here
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\n", output)
// main.MyStruct{Id:"1", Name:"Hello", UserId:"123", CreatedAt:123}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With