You are using the StructTag type to retrieve tags. There are examples in the documentation I refer to, look at them, but your code might 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 also takes care of this, you need to make additional improvements to the PrintFields
function:
- we need to check if the
json
tag -
(ie json:"-"
) - we need to check if the name exists and isolate it
Something like that:
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) } }
source share