diff --git a/json/build.go b/json/build.go index 467aad4..cf67f83 100644 --- a/json/build.go +++ b/json/build.go @@ -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 } diff --git a/json/json_test.go b/json/json_test.go index 4858152..65d4243 100644 --- a/json/json_test.go +++ b/json/json_test.go @@ -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) +} diff --git a/json/parse.go b/json/parse.go index ff4e58b..75274ff 100644 --- a/json/parse.go +++ b/json/parse.go @@ -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是合法的