json_filter/filter.go

233 lines
5.9 KiB
Go

// Package filter ...
//
// Description : filter ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-07-04 17:47
package filter
import (
"encoding/json"
"fmt"
"git.zhangdeman.cn/zhangdeman/wrapper"
"strings"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"errors"
)
// NewFilter 过滤器实例
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:54 2022/7/4
func NewFilter(sourceData string, filterRuleList []MapRule) *filter {
return &filter{
sourceData: sourceData,
formatResult: "{}",
filterRuleList: filterRuleList,
}
}
// filter 数据过滤
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:58 2022/7/4
type filter struct {
sourceData string
formatResult string
filterRuleList []MapRule
}
// Deal ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:59 2022/7/4
func (f *filter) Deal() error {
var (
err error
formatVal interface{}
)
for _, rule := range f.filterRuleList {
if f.IsArray(rule) {
// 对于list的处理
if err = f.handleArray(rule); nil != err {
return err
}
continue
}
sourceResult := gjson.Get(f.sourceData, rule.SourcePath)
if formatVal, err = f.getValue(rule.DataType, sourceResult, rule.DefaultValue); nil != err {
return fmt.Errorf("%s = %v can not convert to %s : %s", rule.SourcePath, sourceResult.Value(), rule.DataType, err.Error())
}
if f.formatResult, err = sjson.Set(f.formatResult, rule.MapPath, formatVal); nil != err {
return err
}
}
return nil
}
// IsArray 判断是否为数组
//
// Author : zhangdeman001@ke.com<张德满>
//
// Date : 17:48 2023/1/1
func (f *filter) IsArray(rule MapRule) bool {
return strings.Contains(rule.SourcePath, "[]")
}
// handleArray 处理数组(最复杂的场景)
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:41 2023/1/1
func (f *filter) handleArray(rule MapRule) error {
var (
err error
)
sourcePathArray := strings.Split(rule.SourcePath, "[]")
for idx, item := range sourcePathArray {
sourcePathArray[idx] = strings.Trim(item, ".")
}
mapPathArray := strings.Split(strings.TrimRight(rule.MapPath, ".[]"), "[]")
for idx, item := range mapPathArray {
mapPathArray[idx] = strings.Trim(item, ".")
}
if len(sourcePathArray) != len(mapPathArray) {
if len(mapPathArray) != 1 {
return errors.New("map rule is invalid")
}
// 提取某一个list下的字段, 组成一个list
res := make([]string, 0)
if len(sourcePathArray[0]) == 0 {
f.getAllFinalData(&res, gjson.Parse(f.sourceData).Array(), sourcePathArray[1:])
} else {
f.getAllFinalData(&res, gjson.Get(f.sourceData, sourcePathArray[0]).Array(), sourcePathArray[1:])
}
if f.formatResult, err = sjson.Set(f.formatResult, mapPathArray[0], res); nil != err {
return err
}
return nil
}
return nil
}
// extraFinalResult 提取全部最底层结果
//
// Author : zhangdeman001@ke.com<张德满>
//
// Date : 14:00 2023/1/2
func (f *filter) getAllFinalData(res *[]string, resultList []gjson.Result, pathArr []string) {
if len(pathArr) == 1 {
for _, item := range resultList {
*res = append(*res, item.Get(pathArr[0]).String())
}
return
}
for _, item := range resultList {
f.getAllFinalData(res, item.Array(), pathArr[1:])
}
return
}
// String 获取格式化之后的字符串
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 21:18 2022/12/31
func (f *filter) String() string {
return f.formatResult
}
// Byte 获取格式化之后的字节数组
//
// Author : zhangdeman001@ke.com<张德满>
//
// Date : 21:18 2022/12/31
func (f *filter) Byte() []byte {
return []byte(f.String())
}
// Parse 解析返回结果
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 21:20 2022/12/31
func (f *filter) Parse(receiver interface{}) error {
if nil == receiver {
return errors.New("receiver is nil")
}
return json.Unmarshal(f.Byte(), receiver)
}
// getValue 获取值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:25 2022/7/4
func (f *filter) getValue(dataType string, sourceValue gjson.Result, defaultValue string) (interface{}, error) {
sourceValueStr := defaultValue
if sourceValue.Exists() {
str := sourceValue.String()
if len(str) > 0 {
sourceValueStr = str
}
}
strVal := wrapper.String(sourceValueStr)
switch dataType {
case wrapper.DataTypeInt8:
return strVal.ToInt8().Value, strVal.ToInt8().Err
case wrapper.DataTypeInt16:
return strVal.ToInt16().Value, strVal.ToInt16().Err
case wrapper.DataTypeInt32:
return strVal.ToInt32().Value, strVal.ToInt32().Err
case wrapper.DataTypeInt64:
return strVal.ToInt64().Value, strVal.ToInt64().Err
case wrapper.DataTypeInt:
return strVal.ToInt().Value, strVal.ToInt().Err
case wrapper.DataTypeUint8:
return strVal.ToUint8().Value, strVal.ToUint8().Err
case wrapper.DataTypeUint16:
return strVal.ToUint16().Value, strVal.ToUint16().Err
case wrapper.DataTypeUint32:
return strVal.ToUint32().Value, strVal.ToUint32().Err
case wrapper.DataTypeUint64:
return strVal.ToUint64().Value, strVal.ToUint64().Err
case wrapper.DataTypeUint:
return strVal.ToUint().Value, strVal.ToUint().Err
case wrapper.DataTypeBool:
return strVal.ToBool().Value, strVal.ToBool().Err
case wrapper.DataTypeFloat32:
return strVal.ToFloat64().Value, strVal.ToFloat64().Err
case wrapper.DataTypeFloat64:
fallthrough
case wrapper.DataTypeFloat:
fallthrough
case wrapper.DataTypeDouble:
return strVal.ToFloat64().Value, strVal.ToFloat64().Err
case wrapper.DataTypeNumber:
return strVal.ToNumber().Value, strVal.ToNumber().Err
case wrapper.DataTypeString:
return sourceValueStr, nil
case wrapper.DataTypeAny:
return sourceValue.Value(), nil
case wrapper.DataTypeAnySlice:
// 任意类型的list
return strVal.ToAnySlice().Value, strVal.ToAnySlice().Err
case wrapper.DataTypeObject:
// object
return strVal.ToObject().Value, strVal.ToObject().Err
default:
return nil, errors.New(dataType + " is not support!")
}
}