function for converting a struct to map in Golang

前端 未结 5 1302
囚心锁ツ
囚心锁ツ 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 18:54

    From struct to map[string]interface{}

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type MyData struct {
        One   int
        Two   string
        Three int
    }
    
    func main() {   
        in := &MyData{One: 1, Two: "second"}
    
        var inInterface map[string]interface{}
        inrec, _ := json.Marshal(in)
        json.Unmarshal(inrec, &inInterface)
    
        // iterate through inrecs
        for field, val := range inInterface {
                fmt.Println("KV Pair: ", field, val)
        }
    }
    

    go playground here

提交回复
热议问题