dongqiulei1987 2014-05-11 06:14
浏览 57
已采纳

在Golang中将结构转换为地图的函数

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).

Edit TL;DR version, Jun 15, 2015

If you want the fast solution for converting a structure to map, see the accepted answer, upvote it and use that package.

Happy coding! :)


Original Post

So far I have this function, I am using the reflect package but I don't understand well how to use the package, please bear with me.

func ConvertToMap(model interface{}) bson.M {
    ret := bson.M{}

    modelReflect := reflect.ValueOf(model)

    if modelReflect.Kind() == reflect.Ptr {
        modelReflect = modelReflect.Elem()
    }

    modelRefType := modelReflect.Type()
    fieldsCount := modelReflect.NumField()

    var fieldData interface{}

    for i := 0; i < fieldsCount; i++ {
        field := modelReflect.Field(i)

        switch field.Kind() {
        case reflect.Struct:
            fallthrough
        case reflect.Ptr:
            fieldData = ConvertToMap(field.Interface())
        default:
            fieldData = field.Interface()
        }

        ret[modelRefType.Field(i).Name] = fieldData
    }

    return ret
}

Also I looked at JSON package source code, because it should contain my needed implementation (or parts of it) but don't understand too much.

  • 写回答

4条回答 默认 最新

  • dpu66046 2014-08-04 11:38
    关注

    I also had need for something like this. I was using an internal package which was converting a struct to a map. I decided to open source it with other struct based high level functions. Have a look:

    https://github.com/fatih/structs

    It has support for:

    • Convert struct to a map
    • Extract the fields of a struct to a []string
    • Extract the values of a struct to a []values
    • Check if a struct is initialized or not
    • Check if a passed interface is a struct or a pointer to struct

    You can see some examples here: http://godoc.org/github.com/fatih/structs#pkg-examples For example converting a struct to a map is a simple:

    type Server struct {
        Name    string
        ID      int32
        Enabled bool
    }
    
    s := &Server{
        Name:    "gopher",
        ID:      123456,
        Enabled: true,
    }
    
    // => {"Name":"gopher", "ID":123456, "Enabled":true}
    m := structs.Map(s)
    

    The structs package has support for anonymous (embedded) fields and nested structs. The package provides to filter certain fields via field tags.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵