コード
package main
import (
"fmt"
"reflect"
"encoding/json"
)
func StructToMap(data interface{}) map[string]interface{} {
result := make(map[string]interface{})
elem := reflect.ValueOf(data).Elem()
size := elem.NumField()
for i := 0; i < size; i++ {
field := elem.Type().Field(i).Name
value := elem.Field(i).Interface()
result[field] = value
}
return result
}
func StructToJsonTagMap(data interface{}) map[string]interface{} {
result := make(map[string]interface{})
elem := reflect.ValueOf(data).Elem()
size := elem.NumField()
for i := 0; i < size; i++ {
field := elem.Type().Field(i).Tag.Get("json")
value := elem.Field(i).Interface()
result[field] = value
}
return result
}
func StructToJsonTagMap2(data interface{}) map[string]interface{} {
result := make(map[string]interface{})
b, _ := json.Marshal(data)
json.Unmarshal(b, &result)
return result
}
type A struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
a := A{1, "keitaj"}
fmt.Println(a)
b := StructToMap(&a)
fmt.Println(b)
c := StructToJsonTagMap(&a)
fmt.Println(c)
d := StructToJsonTagMap2(&a)
fmt.Println(d)
}
実行結果
{1 keitaj}
map[ID:1 Name:keitaj]
map[id:1 name:keitaj]
map[name:keitaj id:1]
備考
Tagをmapのkeyにしたい場合は、StructTag型のGetメソッドを使う
参考記事