From 96ff37647002dee6fa6792c63d986affb4772a19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 5 Dec 2024 18:49:04 +0800 Subject: [PATCH] =?UTF-8?q?sjson=E6=94=AF=E6=8C=81=E8=AE=BE=E7=BD=AEkey?= =?UTF-8?q?=E4=B8=AD=E5=8C=85=E5=90=AB=20.=20=E5=AD=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sjson_hack/set.go | 59 +++++++++++++++++++++++++++++++----------- sjson_hack/set_test.go | 18 +++++++++++++ 2 files changed, 62 insertions(+), 15 deletions(-) create mode 100644 sjson_hack/set_test.go diff --git a/sjson_hack/set.go b/sjson_hack/set.go index f1075a2..809fb11 100644 --- a/sjson_hack/set.go +++ b/sjson_hack/set.go @@ -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 } diff --git a/sjson_hack/set_test.go b/sjson_hack/set_test.go new file mode 100644 index 0000000..b492da9 --- /dev/null +++ b/sjson_hack/set_test.go @@ -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) +}