feat: Slice方法支持JSON字符串自动解析

当Slice()方法遇到字符串类型且内容以'['开头时,会自动尝试JSON解析为切片。
这使得处理JSON格式的数组字符串更加便捷。
This commit is contained in:
2026-01-12 15:04:42 +08:00
parent 39da1d55dd
commit 3915bee7b8

15
rfx.go
View File

@@ -885,7 +885,7 @@ func (r *rfx) StringMap() map[string]any {
} }
// Slice 将当前值转换为 []any 切片 // Slice 将当前值转换为 []any 切片
func (r *rfx) Slice() []any { func (r *rfx) Slice() (result []any) {
v := r.value v := r.value
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
if v.IsNil() { if v.IsNil() {
@@ -893,11 +893,20 @@ func (r *rfx) Slice() []any {
} }
v = v.Elem() v = v.Elem()
} }
if !v.IsValid() || (v.Kind() != reflect.Slice && v.Kind() != reflect.Array) {
if !v.IsValid() {
return nil
} else if v.Kind() == reflect.String {
if str := r.String(); len(str) >= 2 && str[0] == '[' {
if err := json.Unmarshal([]byte(str), &result); err == nil {
return result
}
}
} else if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
return nil return nil
} }
result := make([]any, v.Len()) result = make([]any, v.Len())
for i := 0; i < v.Len(); i++ { for i := 0; i < v.Len(); i++ {
elem := v.Index(i) elem := v.Index(i)
for elem.Kind() == reflect.Ptr || elem.Kind() == reflect.Interface { for elem.Kind() == reflect.Ptr || elem.Kind() == reflect.Interface {