1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-03-01 00:35:28 +08:00

add support json tag attribute for StructToMap function (#78)

This commit is contained in:
zm
2023-03-11 20:08:41 +08:00
committed by GitHub
parent 3857b342f6
commit 1755dd249b
2 changed files with 34 additions and 14 deletions

View File

@@ -253,10 +253,11 @@ func StructToMap(value any) (map[string]any, error) {
for i := 0; i < fieldNum; i++ { for i := 0; i < fieldNum; i++ {
name := t.Field(i).Name name := t.Field(i).Name
tag := t.Field(i).Tag.Get("json") tag := t.Field(i).Tag.Get("json")
if regex.MatchString(name) && tag != "" { if tag == "" || strings.HasPrefix(tag, "-") || !regex.MatchString(name) {
//result[name] = v.Field(i).Interface() continue
result[tag] = v.Field(i).Interface()
} }
tag = strings.Split(tag, ",")[0]
result[tag] = v.Field(i).Interface()
} }
return result, nil return result, nil

View File

@@ -180,18 +180,37 @@ func TestToMap(t *testing.T) {
func TestStructToMap(t *testing.T) { func TestStructToMap(t *testing.T) {
assert := internal.NewAssert(t, "TestStructToMap") assert := internal.NewAssert(t, "TestStructToMap")
type People struct { t.Run("StructToMap", func(t *testing.T) {
Name string `json:"name"` type People struct {
age int Name string `json:"name"`
} age int
p := People{ }
"test", p := People{
100, "test",
} 100,
pm, _ := StructToMap(p) }
pm, _ := StructToMap(p)
var expected = map[string]any{"name": "test"}
assert.Equal(expected, pm)
})
expected := map[string]any{"name": "test"} t.Run("StructToMapWithJsonAttr", func(t *testing.T) {
assert.Equal(expected, pm) type People struct {
Name string `json:"name,omitempty"` // json tag with attribute
Phone string `json:"phone"` // json tag without attribute
Sex string `json:"-"` // ignore
age int // no tag
}
p := People{
"test",
"1111",
"male",
100,
}
pm, _ := StructToMap(p)
var expected = map[string]any{"name": "test", "phone": "1111"}
assert.Equal(expected, pm)
})
} }
func TestMapToSlice(t *testing.T) { func TestMapToSlice(t *testing.T) {