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

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

    switch jsonTag := t.Tag.Get("json"); jsonTag {
    case "-":
    case "":
        fmt.Println(fieldName)
    default:
        parts := strings.Split(jsonTag, ",")
        name := parts[0]
        if name == "" {
            name = fieldName
        }
        fmt.Println(name)
    }
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)