From 71eb39d305987401d4be41df119afc920c088d78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sun, 23 Jan 2022 01:47:55 +0800 Subject: [PATCH] save code --- json_tool/gabs.go | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/json_tool/gabs.go b/json_tool/gabs.go index 4992117..0340693 100644 --- a/json_tool/gabs.go +++ b/json_tool/gabs.go @@ -67,13 +67,24 @@ func (df *DataFilter) Filter() (string, error) { // 创建数据的根结点 jsonObject = gabs.New() for _, item := range df.filterRule { - if strings.Contains(item.SourceKey, "[]") { + if df.pathIsArrayValue(item.SourceKey) { // 数组, 特殊处理 - // 1. 判断数据源数组深度与目标数组深度是否一致 - continue + // 0. 判断目标路径是否为数组 + if !df.pathIsArrayValue(item.MapKey) { + // 目标路径不是数组, 转换为支持list, 后续逻辑会自动提取为list数组 + item.MapKey = item.MapKey + ".[]" + } else { + // 1. 判断数据源数组深度与目标数组深度是否一致 + sourcePathArr := strings.Split(item.SourceKey, ".[].") + mapPathArr := strings.Split(item.MapKey, ".[].") + if len(sourcePathArr) != len(mapPathArr) { + return "", errors.New("slice转化原始数据深度与目标数据深度不一致") + } + continue + } } // 目标位置, 是一个数组 - if strings.HasSuffix(item.MapKey, "[]") { + if df.pathIsArrayValue(item.MapKey) { realMapKey := strings.ReplaceAll(item.MapKey, ".[]", "") if exist := jsonObject.Exists(realMapKey); !exist { if _, err = jsonObject.ArrayP(realMapKey); nil != err { @@ -124,3 +135,12 @@ func (df *DataFilter) getValueType(valueResult gjson.Result) string { } return dataType } + +// pathIsArrayValue 判断路径是否为数组值 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2022/1/23 12:56 AM +func (df *DataFilter) pathIsArrayValue(path string) bool { + return strings.Contains(path, "[]") +}