sjson支持设置key中包含 . 字符
This commit is contained in:
parent
f61f9b28b1
commit
96ff376470
@ -7,7 +7,19 @@
|
||||
// Date : 2024-12-03 11:36
|
||||
package sjson_hack
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.zhangdeman.cn/zhangdeman/json_filter/gjson_hack"
|
||||
"git.zhangdeman.cn/zhangdeman/wrapper"
|
||||
"github.com/tidwall/sjson"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
reg = regexp.MustCompile(`({\{\#.*?\#\}\})`)
|
||||
)
|
||||
|
||||
// Set 设置路径的值
|
||||
//
|
||||
@ -15,25 +27,42 @@ import "strings"
|
||||
//
|
||||
// Date : 11:36 2024/12/3
|
||||
func Set(jsonRes string, path string, value any) (string, error) {
|
||||
if !isPathHasSpecialChar(path) {
|
||||
// 不包含特殊字符
|
||||
fmt.Println(jsonRes, value)
|
||||
var (
|
||||
err error
|
||||
res string = jsonRes
|
||||
)
|
||||
|
||||
// 包含特殊字符串, 匹配出特殊字符串
|
||||
specialKeyList := getSpecialKeyList(path)
|
||||
specialKeyTale := map[string]string{}
|
||||
for _, item := range specialKeyList {
|
||||
// 替换掉占位字符串
|
||||
specialKeyTale[item] = wrapper.StringFromRandom(64, "").Md5().Value
|
||||
path = strings.ReplaceAll(path, item, specialKeyTale[item])
|
||||
}
|
||||
return "", nil
|
||||
|
||||
if res, err = sjson.Set(res, path, value); nil != err {
|
||||
return "", errors.New(path + " -> set json fail:" + err.Error())
|
||||
}
|
||||
|
||||
// 将特殊字符串替换回来
|
||||
for sourceKey, convertKey := range specialKeyTale {
|
||||
res = strings.ReplaceAll(res, convertKey, gjson_hack.GetRealKeyName(sourceKey))
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// isPathHasSpecialChar 判断路径中是否包含特殊字符
|
||||
// getSpecialKeyList 获取特殊key列表
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 11:38 2024/12/3
|
||||
func isPathHasSpecialChar(path string) bool {
|
||||
specialCharList := []string{
|
||||
".",
|
||||
// Date : 17:35 2024/12/5
|
||||
func getSpecialKeyList(path string) []string {
|
||||
matchList := reg.FindAllString(path, -1)
|
||||
if len(matchList) == 0 {
|
||||
return make([]string, 0)
|
||||
}
|
||||
for _, itemChar := range specialCharList {
|
||||
if strings.Contains(path, itemChar) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return matchList
|
||||
}
|
||||
|
18
sjson_hack/set_test.go
Normal file
18
sjson_hack/set_test.go
Normal file
@ -0,0 +1,18 @@
|
||||
// Package sjson_hack ...
|
||||
//
|
||||
// Description : sjson_hack ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2024-12-05 17:32
|
||||
package sjson_hack
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSet(t *testing.T) {
|
||||
res, err := Set("{}", "{{#a.b#}}.c.{{#c.d#}}.e", "test")
|
||||
fmt.Println(res, err)
|
||||
}
|
Loading…
Reference in New Issue
Block a user