58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
// Package json_tool ...
|
|
//
|
|
// Description : json_tool ...
|
|
//
|
|
// Author : go_developer@163.com<张德满>
|
|
//
|
|
// Date : 2022-01-09 10:48 PM
|
|
package json_tool
|
|
|
|
import (
|
|
"github.com/pkg/errors"
|
|
"github.com/tidwall/gjson"
|
|
)
|
|
|
|
// GetJSONDataStruct 获取JSON数据的结构
|
|
//
|
|
// Author : go_developer@163.com<张德满>
|
|
//
|
|
// Date : 10:53 PM 2022/1/9
|
|
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() {
|
|
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, nil
|
|
}
|