Function for Converting a Struct to a Map in Golang
Question:
How can I efficiently convert a struct to a map in Golang, utilizing JSON tags as keys where possible?
Answer:
Third-Party Library:
The structs package by Fatih provides a straightforward and comprehensive solution for this task:
func Map(object interface{}) map[string]interface{}
Usage:
package main import ( "fmt" "github.com/fatih/structs" ) type Server struct { Name string `json:"name"` ID int32 `json:"id"` Enabled bool `json:"enabled"` } func main() { s := &Server{ Name: "gopher", ID: 123456, Enabled: true, } m := structs.Map(s) fmt.Println(m) // Output: {"name":"gopher", "id":123456, "enabled":true} }
Features:
Custom Implementation:
If a custom implementation is preferred, reflect.Struct can be utilized:
func ConvertToMap(model interface{}) map[string]interface{} { // Get the reflect type and value of the model modelType := reflect.TypeOf(model) modelValue := reflect.ValueOf(model) if modelValue.Kind() == reflect.Ptr { modelValue = modelValue.Elem() } // Check if the model is a struct if modelType.Kind() != reflect.Struct { return nil } // Create a new map to store the key-value pairs ret := make(map[string]interface{}) // Iterate over the fields of the struct for i := 0; i < modelType.NumField(); i++ { // Get the field and its name field := modelType.Field(i) fieldName := field.Name // Check if the field has a JSON tag jsonTag := field.Tag.Get("json") if jsonTag != "" { fieldName = jsonTag } // Get the value of the field fieldValue := modelValue.Field(i) // Recursively convert nested structs switch fieldValue.Kind() { case reflect.Struct: ret[fieldName] = ConvertToMap(fieldValue.Interface()) default: ret[fieldName] = fieldValue.Interface() } } return ret }
However, this requires manually extracting the field names and converting nested structs.
The above is the detailed content of How to Efficiently Convert a Go Struct to a Map Using JSON Tags?. For more information, please follow other related articles on the PHP Chinese website!