dtr84664 2019-04-27 09:22 采纳率: 100%
浏览 421
已采纳

Golang通过JSON标记获取结构的字段名称

I have a struct:

type Human struct {
    Head  string  `json:"a1"`
    Body  string  `json:"a2"`
    Leg   string  `json:"a3"`
}

How can I get the struct's field name by providing JSON tag name? Probably something like this:

fmt.Println(getFieldName("a1")) // "Head"
fmt.Println(getFieldName("a2")) // "Body"
fmt.Println(getFieldName("a99")) // ""

func getFieldName(tag string) (fieldname string) {
    /* ... */
}

How should I implement the getFieldName function? I read online, it seems I need to use the reflect package, hmmm... any helping hand? :)

  • 写回答

1条回答 默认 最新

  • duanaoou4105 2019-04-30 13:53
    关注

    You can use the reflect package to loop over a struct's fields and match against their tag values.

    func getFieldName(tag, key string, s interface{}) (fieldname string) {
        rt := reflect.TypeOf(s)
        if rt.Kind() != reflect.Struct {
            panic("bad type")
        }
        for i := 0; i < rt.NumField(); i++ {
            f := rt.Field(i)
            v := strings.Split(f.Tag.Get(key), ",")[0] // use split to ignore tag "options" like omitempty, etc.
            if v == tag {
                return f.Name
            }
        }
        return ""
    }
    

    https://play.golang.com/p/2zCC7pZKJTz


    Alternatively, as pointed out by @icza, you can build up a map and then use that for quicker lookups.

    //                         Human            json       a1     Head
    var fieldsByTag = make(map[reflect.Type]map[string]map[string]string)
    
    func buildFieldsByTagMap(key string, s interface{}) {
        rt := reflect.TypeOf(s)
        if rt.Kind() != reflect.Struct {
            panic("bad type")
        }
    
        if fieldsByTag[rt] == nil {
            fieldsByTag[rt] = make(map[string]map[string]string)
        }
        if fieldsByTag[rt][key] == nil {
            fieldsByTag[rt][key] = make(map[string]string)
        }
    
        for i := 0; i < rt.NumField(); i++ {
            f := rt.Field(i)
            v := strings.Split(f.Tag.Get(key), ",")[0] // use split to ignore tag "options"
            if v == "" || v == "-" {
                continue
            }
            fieldsByTag[rt][key][v] = f.Name
        }
    }
    

    https://play.golang.com/p/qlt_mWsXGju

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件
  • ¥150 求 《小魔指》街机游戏机整合模拟软件
  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗
  • ¥20 双非跨考工科哪个专业和方向就业前景好?