gopkg/json_tool/parse.go

58 lines
1.3 KiB
Go
Raw Normal View History

// Package json_tool ...
//
// Description : json_tool ...
//
// Author : go_developer@163.com<张德满>
//
// Date : 2022-01-09 10:48 PM
package json_tool
import (
2022-01-10 14:21:48 +08:00
"github.com/pkg/errors"
"github.com/tidwall/gjson"
)
// GetJSONDataStruct 获取JSON数据的结构
//
// Author : go_developer@163.com<张德满>
//
// Date : 10:53 PM 2022/1/9
2022-01-10 14:21:48 +08:00
func GetJSONDataStruct(data string) ([]string, error) {
if !gjson.Valid(data) {
return make([]string, 0), errors.New("JSON format is invalid")
}
pathList := make([]string, 0)
r := gjson.Parse(data)
r.ForEach(func(key, value gjson.Result) bool {
if value.IsObject() {
2022-01-10 14:21:48 +08:00
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 {
2022-01-10 14:21:48 +08:00
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
})
2022-01-10 14:21:48 +08:00
return pathList, nil
}