dongxuxian1123 2016-11-29 11:30
浏览 782
已采纳

如何在golang中获取结构的json字段名称?

What is the way to get the json field names of this struct ?

type example struct {
    Id          int `json:"id"`
    CreatedAt   string `json:"created_at"`
    Tag         string `json:"tag"`
    Text        string `json:"text"`
    AuthorId    int `json:"author_id"`
}

I try to print the fields with this function :

func (b example) PrintFields() {
    val := reflect.ValueOf(b)
    for i := 0; i < val.Type().NumField(); i++ {
        fmt.Println(val.Type().Field(i).Name)
    }
}

Of course I get :

Id
CreatedAt
Tag
Text
AuthorId

But I would like something like :

id
created_at
tag
text
author_id
  • 写回答

5条回答 默认 最新

  • dongpangfu6322 2016-11-29 11:40
    关注

    You use the StructTag type to get the tags. The documentation I linked has examples, look them up, but your code could be something like

    func (b example) PrintFields() {
        val := reflect.ValueOf(b)
        for i := 0; i < val.Type().NumField(); i++ {
            fmt.Println(val.Type().Field(i).Tag.Get("json"))
        }
    }
    

    NOTE The json tag format supports more than just field names, such as omitempty or string, so if you need an approach that takes care of that too, further improvements to the PrintFields function should be made:

    1. we need to check whether the json tag is - (i.e. json:"-")
    2. we need to check if name exists and isolate it

    Something like this:

    func (b example) PrintFields() {
        val := reflect.ValueOf(b)
        for i := 0; i < val.Type().NumField(); i++ {
            t := val.Type().Field(i)
            fieldName := t.Name
    
            if jsonTag := t.Tag.Get("json"); jsonTag != "" && jsonTag != "-" {
                if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 {
                    fieldName = jsonTag[:commaIdx]
                }
            }
    
    
            fmt.Println(fieldName)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥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键失灵