gjson读取参数支持key名称中包含.
This commit is contained in:
@ -242,3 +242,82 @@ func Result(gjsonResult gjson.Result) gjson.Result {
|
||||
}
|
||||
return Object(gjsonResult)
|
||||
}
|
||||
|
||||
// Get 主要解决 key 中包含 . 的问题
|
||||
//
|
||||
// 如 : {"person.name": "test"} 如何将 person.name 整体作为一个字段而非两个层级
|
||||
//
|
||||
// 解决方案 :
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 20:17 2024/12/4
|
||||
func Get(gjsonResult gjson.Result, path string) gjson.Result {
|
||||
if len(path) == 0 {
|
||||
return gjsonResult
|
||||
}
|
||||
if !gjsonResult.Exists() {
|
||||
return gjsonResult
|
||||
}
|
||||
if !gjsonResult.IsObject() && !gjsonResult.IsArray() {
|
||||
return gjsonResult
|
||||
}
|
||||
if !IsSpecialPath(path) {
|
||||
// 不是特殊路径
|
||||
return gjsonResult
|
||||
}
|
||||
pathArr := strings.Split(path, ".")
|
||||
normalPathList := make([]string, 0)
|
||||
specialKeyList := make([]string, 0)
|
||||
specialKeyHasStart := false
|
||||
for idx, item := range pathArr {
|
||||
if strings.HasPrefix(item, SpecialKeyStart) {
|
||||
specialKeyHasStart = true
|
||||
specialKeyList = append(specialKeyList, item)
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(item, SpecialKeyEnd) {
|
||||
specialKeyHasStart = false
|
||||
specialKeyList = append(specialKeyList, item)
|
||||
sourceResult := gjsonResult
|
||||
if len(normalPathList) > 0 {
|
||||
sourceResult = gjsonResult.Get(strings.Join(normalPathList, "."))
|
||||
}
|
||||
realKeyName := GetRealKeyName(strings.Join(specialKeyList, "."))
|
||||
return Get(sourceResult.Map()[realKeyName], strings.Join(pathArr[idx+1:], "."))
|
||||
}
|
||||
if specialKeyHasStart {
|
||||
specialKeyList = append(specialKeyList, item)
|
||||
continue
|
||||
}
|
||||
normalPathList = append(normalPathList, item)
|
||||
}
|
||||
return gjsonResult
|
||||
}
|
||||
|
||||
// IsSpecialPath 判断传入的是否为特殊路径
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 20:27 2024/12/4
|
||||
func IsSpecialPath(path string) bool {
|
||||
return strings.Contains(path, SpecialKeyStart) && strings.Contains(path, SpecialKeyEnd)
|
||||
}
|
||||
|
||||
// IsSpecialKey 判断是否特殊key
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 20:29 2024/12/4
|
||||
func IsSpecialKey(key string) bool {
|
||||
return strings.HasPrefix(key, SpecialKeyStart) && strings.HasSuffix(key, SpecialKeyEnd)
|
||||
}
|
||||
|
||||
// GetRealKeyName ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 20:31 2024/12/4
|
||||
func GetRealKeyName(key string) string {
|
||||
return strings.TrimSuffix(strings.TrimPrefix(key, SpecialKeyStart), SpecialKeyEnd)
|
||||
}
|
||||
|
Reference in New Issue
Block a user