69 lines
1.5 KiB
Go

// Package sjson_hack ...
//
// Description : sjson_hack ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-12-03 11:36
package sjson_hack
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 设置路径的值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:36 2024/12/3
func Set(jsonRes string, path string, value any) (string, error) {
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])
}
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
}
// getSpecialKeyList 获取特殊key列表
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:35 2024/12/5
func getSpecialKeyList(path string) []string {
matchList := reg.FindAllString(path, -1)
if len(matchList) == 0 {
return make([]string, 0)
}
return matchList
}