refactor(common):优化JSON清理逻辑

- 使用gjson.NewWithOptions替代gjson.DecodeToJson解析JSON字符串- 添加日志记录清理过程中的JSON数据
- 修改cleanData函数参数类型为interface{}
- 更新错误处理逻辑并添加错误日志
- 调整JSON编码方式,使用ToJson()方法返回结果
- 移除不必要的类型转换和中间变量声明
main v1.0.19
maguodong 2025-11-12 15:05:04 +08:00
parent aab78082ce
commit b10df1f064
1 changed files with 9 additions and 11 deletions

View File

@ -4,26 +4,24 @@ import (
"reflect" "reflect"
"github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/glog"
) )
// CleanJSON 清理JSON字符串中的空值和0值字段 // CleanJSON 清理JSON字符串中的空值和0值字段
func CleanJSON(jsonStr string) ([]byte, error) { func CleanJSON(jsonStr string) ([]byte, error) {
// 解析为JSON // 解析为JSON
json, err := gjson.DecodeToJson(jsonStr, gjson.Options{StrNumber: true}) //var data interface{}
if err != nil { json := gjson.NewWithOptions(jsonStr, gjson.Options{StrNumber: true})
return nil, err glog.Infof(gctx.New(), "Cleaning JSON: %+v", json)
}
// 递归清理数据 // 递归清理数据
cleaned := cleanData(json) cleaned := cleanData(json.Interface())
jsons, err := gjson.DecodeToJson(cleaned, gjson.Options{StrNumber: true})
// 转换回JSON字符串
result, err := gjson.Marshal(cleaned)
if err != nil { if err != nil {
glog.Errorf(gctx.New(), "Error decoding JSON: %v", err)
return nil, err return nil, err
} }
return jsons.ToJson()
return result, nil
} }
// cleanData 递归清理map或slice中的空值和0值 // cleanData 递归清理map或slice中的空值和0值