ZGGSONG WIKI

Go结构体转Map

结构体转map有两种方式:

  1. 借助json
  2. 使用"github.com/fatih/structs"

结构体 -> json -> map

但是可能会修改掉变量类型

type Student struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func TestT1(t *testing.T) {
    s1 := Student{
    	Name: "张三",
    	Age:  18,
    }
    //struct to json
    jsonRet, jsonErr := json.Marshal(s1)
    require.Equal(t, jsonErr, nil)
    fmt.Println("jsonRet: ", string(jsonRet))

    //json to map
    var mapRet map[string]interface{}
    errUnmarshal := json.Unmarshal(jsonRet, &mapRet)
    require.Equal(t, errUnmarshal, nil)
    fmt.Println("mapRet: ", mapRet)

    //FIXME: value 类型有问题
    for k, v := range mapRet {
    	fmt.Printf("key: %v, value: %v, typeOfValue: %T\n", k, v, v)
    	/*
    		key: name, value: 张三, typeOfValue: string
    		key: age, value: 18, typeOfValue: float64
    	*/
    }
}

使用"github.com/fatih/structs"

type Student struct {
    Name string `json:"name" structs:"user_name"`
    Age  int    `json:"age" structs:"user_age"`
}

func TestT2(t *testing.T) {
    s2 := Student{
    	Name: "张三",
    	Age:  18,
    }

    mapRet := structs.Map(&s2)
    fmt.Println("mapRes: ", mapRet)

    for k, v := range mapRet {
    	fmt.Printf("key: %v, value: %v, typeOfValue: %T\n", k, v, v)
    }
}
Copyright © 2022 ZGGSONG