improve package gjson

This commit is contained in:
John Guo 2022-02-23 16:54:15 +08:00
parent 8eb9fdfcd0
commit e4d56e7ad9
3 changed files with 27 additions and 24 deletions

View File

@ -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 {

View File

@ -67,40 +67,32 @@ 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:
pointedData = data
}
j = &Json{
p: &data,
p: &pointedData,
c: byte(defaultSplitChar),
vc: false,
}
}
}
j.mu = rwmutex.New(options.Safe)
return j
}

View File

@ -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"}`)
})
}