From 61c8bdbf27bebf2e7a5d7b8d8de3ff5380c9a0f6 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Sun, 19 Apr 2020 20:28:13 +0900 Subject: [PATCH] Support custom key name --- encode.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/encode.go b/encode.go index c1994ea..434e7b4 100644 --- a/encode.go +++ b/encode.go @@ -4,6 +4,7 @@ import ( "fmt" "reflect" "strconv" + "strings" "sync" "unsafe" @@ -230,11 +231,19 @@ func (e *Encoder) compileStruct(v reflect.Value) (EncodeOp, error) { opQueue := make([]EncodeOp, 0, fieldNum) for i := 0; i < fieldNum; i++ { field := typ.Field(i) + keyName := field.Name + tag := field.Tag.Get("json") + opts := strings.Split(tag, ",") + if len(opts) > 0 { + if opts[0] != "" { + keyName = opts[0] + } + } op, err := e.compile(v.Field(i)) if err != nil { return nil, err } - key := fmt.Sprintf(`"%s":`, field.Name) + key := fmt.Sprintf(`"%s":`, keyName) opQueue = append(opQueue, func(enc *Encoder, base uintptr) { enc.EncodeString(key) op(enc, base+field.Offset)