Skip to content

Instantly share code, notes, and snippets.

@Kangaroux
Created May 20, 2021 02:40
Show Gist options
  • Save Kangaroux/2e481b8b4fdc571ad6ee65fb4011f7c3 to your computer and use it in GitHub Desktop.
Save Kangaroux/2e481b8b4fdc571ad6ee65fb4011f7c3 to your computer and use it in GitHub Desktop.
Golang: Parse JSON field name from a struct field
// ParseFieldName takes a reflected struct field and returns the JSON name for the field,
// as well if the field is ignored by JSON (using `json:"-"`).
func ParseFieldName(f reflect.StructField) (name string, ignore bool) {
tag := f.Tag.Get("json")
if tag == "" {
return f.Name, false
}
if tag == "-" {
return "", true
}
if i := strings.Index(tag, ","); i != -1 {
if i == 0 {
return f.Name, false
} else {
return tag[:i], false
}
}
return tag, false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment