Last active
February 3, 2022 14:46
-
-
Save vidhill/bc7297c1672b600b8c5f395cbf611047 to your computer and use it in GitHub Desktop.
Go: get the value of the json tag from a `struct` instance
This file contains hidden or 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
module dummy/foo | |
go 1.14 | |
require ( | |
) |
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
doggo := Dog{ | |
Name: "Fluffy", | |
} | |
fieldName, e := getJsonTagValue(doggo, "Name") | |
if e != nil { | |
fmt.Println(e.Error()) | |
return | |
} | |
fmt.Println(fieldName) | |
} |
This file contains hidden or 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
// main logic sourced from https://stackoverflow.com/a/69061124 | |
package main | |
import ( | |
"fmt" | |
"reflect" | |
"strings" | |
) | |
type Dog struct { | |
Name string `json:"bar,omitempty"` | |
} | |
func getStructTag(f reflect.StructField, tagName string) string { | |
return string(f.Tag.Get(tagName)) | |
} | |
// based on the function used in the go standard library "encoding/json" source | |
// https://cs.opensource.google/go/go/+/refs/tags/go1.17.6:src/encoding/json/tags.go;l=17 | |
func extractFieldName(tag string) string { | |
if idx := strings.Index(tag, ","); idx != -1 { | |
return tag[:idx] | |
} | |
return tag | |
} | |
func GetStructField(f Dog, fieldName string) (reflect.StructField, error) { | |
field, ok := reflect.TypeOf(&f).Elem().FieldByName(fieldName) | |
if !ok { | |
emptyValue := reflect.StructField{} | |
return emptyValue, fmt.Errorf(`the field with the name "%s" was not found`, fieldName) | |
} | |
return field, nil | |
} | |
// Returns the json tag for a given struct field | |
func getJsonTagValue(f Dog, fieldName string) (string, error) { | |
field, err := GetStructField(f, fieldName) | |
tag := getStructTag(field, "json") | |
return extractFieldName(tag), err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment