Compare commits

..

2 Commits

3 changed files with 96 additions and 2 deletions

View File

@ -20,7 +20,7 @@ import (
"git.zhangdeman.cn/zhangdeman/gopkg/util"
)
// NewParseJSONTree 获取解析的实例
// NewFilter 获取解析的实例
//
// Author : go_developer@163.com<白茶清欢>
//
@ -32,7 +32,7 @@ func NewFilter(data interface{}, rule map[string]string) *Filter {
}
}
// ParseJSONTree 解析json树
// Filter 解析json树
//
// Author : go_developer@163.com<白茶清欢>
//

View File

@ -8,6 +8,7 @@
package json_tool
import (
"encoding/json"
"fmt"
"testing"
)
@ -84,3 +85,43 @@ func TestSelect(t *testing.T) {
}
fmt.Println(d.String())
}
// TestParse 测试获取JSON数据结构
//
// Author : go_developer@163.com<张德满>
//
// Date : 10:59 PM 2022/1/9
func TestParse(t *testing.T) {
source := map[string]interface{}{
"name": "zhangdeman",
"extra": map[string]interface{}{
"age": 18,
"height": 180,
"slice": []int{1, 2, 3},
"obj": map[string]interface{}{
"la": "aaaa",
},
},
"slice": []int{1, 2, 3},
"map": map[string]interface{}{"a": 1, "b": 2, "c": 4},
"table": []map[string]interface{}{
{"name": "alex", "age": 18, "number": 1, "obj": map[string]interface{}{"enen": "en"}},
{"name": "bob", "age": 28, "number": 2},
},
"two_slice": []map[string]interface{}{
{
"students": []map[string]interface{}{
{
"name": "enen",
"age": 18,
"score": []float64{1, 2, 3, 45},
},
},
"other": []interface{}{"others"},
"read_only": 1,
},
},
}
byteData, _ := json.Marshal(source)
fmt.Println(GetJSONDataStruct(string(byteData)))
}

53
json_tool/parse.go Normal file
View File

@ -0,0 +1,53 @@
// Package json_tool ...
//
// Description : json_tool ...
//
// Author : go_developer@163.com<张德满>
//
// Date : 2022-01-09 10:48 PM
package json_tool
import (
"github.com/tidwall/gjson"
)
// GetJSONDataStruct 获取JSON数据的结构
//
// Author : go_developer@163.com<张德满>
//
// Date : 10:53 PM 2022/1/9
func GetJSONDataStruct(data string) []string {
pathList := make([]string, 0)
r := gjson.Parse(data)
r.ForEach(func(key, value gjson.Result) bool {
if value.IsObject() {
list := GetJSONDataStruct(value.String())
for _, k := range list {
pathList = append(pathList, key.String()+"."+k)
}
}
if value.IsArray() {
dataList := value.Array()
if len(dataList) > 0 {
if !dataList[0].IsObject() && !dataList[0].IsArray() {
pathList = append(pathList, key.String())
} else {
list := GetJSONDataStruct(dataList[0].String())
for _, k := range list {
pathList = append(pathList, key.String()+".[]."+k)
}
}
} else {
pathList = append(pathList, key.String())
}
}
if !value.IsObject() && !value.IsArray() {
pathList = append(pathList, key.String())
}
return true
})
return pathList
}