支持提取指定的值到一个字段,形成列表

This commit is contained in:
2023-01-02 22:12:48 +08:00
parent 123c22e8b2
commit 3dff92188f
4 changed files with 60 additions and 42 deletions

View File

@ -10,9 +10,10 @@ package filter
import (
"encoding/json"
"fmt"
"github.com/tidwall/sjson"
"strings"
"github.com/tidwall/sjson"
"git.zhangdeman.cn/zhangdeman/util"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
@ -102,14 +103,24 @@ func (f *filter) handleArray(rule MapRule) error {
)
sourcePathArray := strings.Split(rule.SourcePath, "[]")
mapPathArray := strings.Split(rule.MapPath, "[]")
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)
f.getAllFinalData(res, gjson.Get(f.sourceData, sourcePathArray[0]).Array(), sourcePathArray[1:])
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
}
@ -123,15 +134,15 @@ func (f *filter) handleArray(rule MapRule) error {
// Author : zhangdeman001@ke.com<张德满>
//
// Date : 14:00 2023/1/2
func (f *filter) getAllFinalData(res []string, resultList []gjson.Result, pathArr []string) {
if len(pathArr) == 0 {
func (f *filter) getAllFinalData(res *[]string, resultList []gjson.Result, pathArr []string) {
if len(pathArr) == 1 {
for _, item := range resultList {
res = append(res, item.String())
*res = append(*res, item.Get(pathArr[0]).String())
}
return
}
for _, item := range resultList {
f.extraFinalResult(res, item.Array(), pathArr[1:])
f.getAllFinalData(res, item.Array(), pathArr[1:])
}
return
}