Lambert Teisserenc Lambert Teisserenc - 3 days ago 6
JSON Question

How to get the json field names of a struct in golang?

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

ain ain
Answer

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"))
    }
}
Comments