-
-
Save Kangaroux/2e481b8b4fdc571ad6ee65fb4011f7c3 to your computer and use it in GitHub Desktop.
Golang: Parse JSON field name from a struct field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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