function for converting a struct to map in Golang

前端 未结 5 1275
囚心锁ツ
囚心锁ツ 2020-12-07 18:38

I want to convert a struct to map in Golang. It would also be nice if I could use the JSON tags as keys in the created map (otherwise defaulting to field name).

Edi

5条回答
  •  轮回少年
    2020-12-07 19:03

    I like the importable package for the accepted answer, but it does not translate my json aliases. Most of my projects have a helper function/class that I import.

    Here is a function that solves my specific problem.

    
    // Converts a struct to a map while maintaining the json alias as keys
    func StructToMap(obj interface{}) (newMap map[string]interface{}, err error) {
        data, err := json.Marshal(obj) // Convert to a json string
    
        if err != nil {
            return
        }
    
        err = json.Unmarshal(data, &newMap) // Convert to a map
        return
    }
    
    

    And in the main, this is how it would be called...

    package main
    
    import (
        "fmt"
        "encoding/json"
        "github.com/fatih/structs"
    )
    
    type MyStructObject struct {
        Email string `json:"email_address"`
    }
    
    func main() {
        obj := &MyStructObject{Email: "test@test.com"}
    
        // My solution
        fmt.Println(StructToMap(obj)) // prints {"email_address": "test@test.com"}
    
        // The currently accepted solution
        fmt.Println(structs.Map(obj)) // prints {"Email": "test@test.com"}
    }
    

提交回复
热议问题