小编lam*_*her的帖子

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

获取此结构的json字段名称的方法是什么?

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"`
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用此功能打印字段:

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

我当然得到:

Id
CreatedAt
Tag
Text
AuthorId
Run Code Online (Sandbox Code Playgroud)

但我想要的是:

id
created_at
tag
text
author_id
Run Code Online (Sandbox Code Playgroud)

json struct field go

16
推荐指数
2
解决办法
1万
查看次数

标签 统计

field ×1

go ×1

json ×1

struct ×1