Skip to content

Instantly share code, notes, and snippets.

@vidhill
Last active February 3, 2022 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vidhill/bc7297c1672b600b8c5f395cbf611047 to your computer and use it in GitHub Desktop.
Save vidhill/bc7297c1672b600b8c5f395cbf611047 to your computer and use it in GitHub Desktop.
Go: get the value of the json tag from a `struct` instance
module dummy/foo
go 1.14
require (
)
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)
}
// 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