Compare commits

...

2 Commits

Author SHA1 Message Date
186f103fa5 merge feature/json 2022-01-10 14:30:26 +08:00
3f2f10c9c2 增加json格式合法性校验 2022-01-10 14:21:48 +08:00

View File

@ -8,6 +8,7 @@
package json_tool package json_tool
import ( import (
"github.com/pkg/errors"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
@ -16,12 +17,15 @@ import (
// Author : go_developer@163.com<张德满> // Author : go_developer@163.com<张德满>
// //
// Date : 10:53 PM 2022/1/9 // Date : 10:53 PM 2022/1/9
func GetJSONDataStruct(data string) []string { func GetJSONDataStruct(data string) ([]string, error) {
if !gjson.Valid(data) {
return make([]string, 0), errors.New("JSON format is invalid")
}
pathList := make([]string, 0) pathList := make([]string, 0)
r := gjson.Parse(data) r := gjson.Parse(data)
r.ForEach(func(key, value gjson.Result) bool { r.ForEach(func(key, value gjson.Result) bool {
if value.IsObject() { if value.IsObject() {
list := GetJSONDataStruct(value.String()) list, _ := GetJSONDataStruct(value.String())
for _, k := range list { for _, k := range list {
pathList = append(pathList, key.String()+"."+k) pathList = append(pathList, key.String()+"."+k)
} }
@ -33,7 +37,7 @@ func GetJSONDataStruct(data string) []string {
if !dataList[0].IsObject() && !dataList[0].IsArray() { if !dataList[0].IsObject() && !dataList[0].IsArray() {
pathList = append(pathList, key.String()) pathList = append(pathList, key.String())
} else { } else {
list := GetJSONDataStruct(dataList[0].String()) list, _ := GetJSONDataStruct(dataList[0].String())
for _, k := range list { for _, k := range list {
pathList = append(pathList, key.String()+".[]."+k) pathList = append(pathList, key.String()+".[]."+k)
} }
@ -49,5 +53,5 @@ func GetJSONDataStruct(data string) []string {
return true return true
}) })
return pathList return pathList, nil
} }