From e4d56e7ad9a99b9bc457b2f0ecadfc89cde134cf Mon Sep 17 00:00:00 2001 From: John Guo Date: Wed, 23 Feb 2022 16:54:15 +0800 Subject: [PATCH] improve package gjson --- encoding/gjson/gjson.go | 3 ++ encoding/gjson/gjson_api_new_load.go | 40 ++++++++----------- .../gjson/gjson_z_unit_feature_set_test.go | 8 ++++ 3 files changed, 27 insertions(+), 24 deletions(-) diff --git a/encoding/gjson/gjson.go b/encoding/gjson/gjson.go index e35a7b026..c7938ad3f 100644 --- a/encoding/gjson/gjson.go +++ b/encoding/gjson/gjson.go @@ -90,6 +90,9 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { // Delete item from map. delete((*pointer).(map[string]interface{}), array[i]) } else { + if (*pointer).(map[string]interface{}) == nil { + *pointer = map[string]interface{}{} + } (*pointer).(map[string]interface{})[array[i]] = value } } else { diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index 367657fa5..75f8e7bef 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -67,38 +67,30 @@ func NewWithOptions(data interface{}, options Options) *Json { } } default: - var reflectInfo = utils.OriginValueAndKind(data) + var ( + pointedData interface{} + reflectInfo = utils.OriginValueAndKind(data) + ) switch reflectInfo.OriginKind { case reflect.Slice, reflect.Array: - var i interface{} = gconv.Interfaces(data) - j = &Json{ - p: &i, - c: byte(defaultSplitChar), - vc: false, - } + pointedData = gconv.Interfaces(data) + case reflect.Map: - var i interface{} = gconv.MapDeep(data, options.Tags) - j = &Json{ - p: &i, - c: byte(defaultSplitChar), - vc: false, - } + pointedData = gconv.MapDeep(data, options.Tags) + case reflect.Struct: if v, ok := data.(iVal); ok { return NewWithOptions(v.Val(), options) } - var i interface{} = gconv.MapDeep(data, options.Tags) - j = &Json{ - p: &i, - c: byte(defaultSplitChar), - vc: false, - } + pointedData = gconv.MapDeep(data, options.Tags) + default: - j = &Json{ - p: &data, - c: byte(defaultSplitChar), - vc: false, - } + pointedData = data + } + j = &Json{ + p: &pointedData, + c: byte(defaultSplitChar), + vc: false, } } j.mu = rwmutex.New(options.Safe) diff --git a/encoding/gjson/gjson_z_unit_feature_set_test.go b/encoding/gjson/gjson_z_unit_feature_set_test.go index 003682a5d..a389d0f79 100644 --- a/encoding/gjson/gjson_z_unit_feature_set_test.go +++ b/encoding/gjson/gjson_z_unit_feature_set_test.go @@ -339,3 +339,11 @@ func Test_Set_GArray(t *testing.T) { t.Assert(j.Get("arr").Array(), g.Slice{"test"}) }) } + +func Test_Set_WithEmptyStruct(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + j := gjson.New(&struct{}{}) + t.AssertNil(j.Set("aa", "123")) + t.Assert(j.MustToJsonString(), `{"aa":"123"}`) + }) +}