增加基础类型的动态提取
This commit is contained in:
parent
6a35eb1a9d
commit
89349705fd
@ -288,7 +288,7 @@ func (dj *DynamicJSON) createNode(parent *JSONode, key string, value interface{}
|
||||
if nil == parent {
|
||||
return errors.New("create node error : parent id nil")
|
||||
}
|
||||
_ = dj.lock.Lock("")
|
||||
_ = dj.lock.Lock()
|
||||
if parent.Child == nil {
|
||||
parent.Child = make([]*JSONode, 0)
|
||||
}
|
||||
@ -310,7 +310,7 @@ func (dj *DynamicJSON) createNode(parent *JSONode, key string, value interface{}
|
||||
}
|
||||
parent.Child = append(parent.Child, newNode)
|
||||
dj.nodeCnt++
|
||||
_ = dj.lock.Unlock("")
|
||||
_ = dj.lock.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -48,3 +48,23 @@ func TestJSON(t *testing.T) {
|
||||
func TestType(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
// TestSelect 测试动态选择字段
|
||||
//
|
||||
// Author : go_developer@163.com<张德满>
|
||||
//
|
||||
// Date : 9:47 下午 2021/4/13
|
||||
func TestSelect(t *testing.T) {
|
||||
source := map[string]interface{}{
|
||||
"name": "zhangdeman",
|
||||
"extra": map[string]interface{}{
|
||||
"age": 18,
|
||||
"height": 180,
|
||||
"slice": []int{1, 2, 3},
|
||||
},
|
||||
"slice": []int{1, 2, 3},
|
||||
}
|
||||
pathList := []string{"name", "extra.age", "slice"}
|
||||
r, e := NewParseJSONTree(source).Parse(pathList)
|
||||
fmt.Println(r.String(), e)
|
||||
}
|
||||
|
@ -10,6 +10,11 @@ package json
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/go-developer/gopkg/util"
|
||||
)
|
||||
@ -37,8 +42,25 @@ type ParseJSONTree struct {
|
||||
// Author : go_developer@163.com<张德满>
|
||||
//
|
||||
// Date : 10:44 下午 2021/3/14
|
||||
func (pjt *ParseJSONTree) Parse() (*JSONode, error) {
|
||||
return nil, nil
|
||||
func (pjt *ParseJSONTree) Parse(pathList []string) (*DynamicJSON, error) {
|
||||
if !pjt.isLegalData() {
|
||||
return nil, errors.New("非法的数据,无法转换成json")
|
||||
}
|
||||
result := NewDynamicJSON()
|
||||
byteData, _ := json.Marshal(pjt.data)
|
||||
source := string(byteData)
|
||||
for _, path := range pathList {
|
||||
// 为数组的处理
|
||||
pathArr := strings.Split(path, "[]")
|
||||
for idx, item := range pathArr {
|
||||
if len(pathArr)-1 == idx {
|
||||
// 当前是最后一项,说明不是数组
|
||||
result.SetValue(item, gjson.Get(source, item).Raw)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// isLegalData 判断是否能转换成json结构, 只有slice/map/struct/能转换成slice或map的[]byte是合法的
|
||||
|
Loading…
Reference in New Issue
Block a user