From 89349705fdb0202aac0ff38336e535a4bd3ddf08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=BE=B7=E6=BB=A1?= Date: Tue, 13 Apr 2021 21:53:36 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=9F=BA=E7=A1=80=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E7=9A=84=E5=8A=A8=E6=80=81=E6=8F=90=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- json/build.go | 4 ++-- json/json_test.go | 20 ++++++++++++++++++++ json/parse.go | 26 ++++++++++++++++++++++++-- 3 files changed, 46 insertions(+), 4 deletions(-) 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是合法的