From 042aad254b46b957d1c2f434f8629ea8a7c88362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 6 May 2025 12:22:26 +0800 Subject: [PATCH] =?UTF-8?q?IJsonRead=E6=94=AF=E6=8C=81Value,=20=E6=B3=9B?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- abstract/json_read.go | 2 ++ filter.go | 22 ++++++++++++++++++++++ implement/gjson_read.go | 6 ++++++ 3 files changed, 30 insertions(+) diff --git a/abstract/json_read.go b/abstract/json_read.go index e2058d2..e9c07a8 100644 --- a/abstract/json_read.go +++ b/abstract/json_read.go @@ -31,4 +31,6 @@ type IJsonRead interface { Array(dataPath string) ([]any, error) // ArrayWithReceiver 通过指针接收 ArrayWithReceiver(dataPath string, receiver any) error + // Value 自适应类型数据读取 + Value(dataPath string, dataType string, defaultValue any) (any, error) } diff --git a/filter.go b/filter.go index 07233ec..7281ab0 100644 --- a/filter.go +++ b/filter.go @@ -10,6 +10,8 @@ package filter import ( "encoding/json" "fmt" + "git.zhangdeman.cn/zhangdeman/json_filter/abstract" + "git.zhangdeman.cn/zhangdeman/json_filter/implement" "reflect" "strings" @@ -21,6 +23,22 @@ import ( "errors" ) +func NewFilterWithJson(sourceData string, filterRuleList []MapRule, jsonRead abstract.IJsonRead, jsonWrite abstract.IJsonWrite) *filter { + if nil == jsonRead { + jsonRead = implement.NewGjsonRead(sourceData) + } + if nil == jsonWrite { + jsonWrite = implement.NewSjsonWrite() + } + return &filter{ + jsonRaad: jsonRead, + jsonWrite: jsonWrite, + sourceData: sourceData, + formatResult: "", + filterRuleList: filterRuleList, + } +} + // NewFilter 过滤器实例 // // Author : go_developer@163.com<白茶清欢> @@ -30,6 +48,8 @@ func NewFilter(sourceData string, filterRuleList []MapRule) *filter { return &filter{ sourceData: sourceData, formatResult: "{}", + jsonRaad: implement.NewGjsonRead(sourceData), + jsonWrite: implement.NewSjsonWrite(), filterRuleList: filterRuleList, } } @@ -40,6 +60,8 @@ func NewFilter(sourceData string, filterRuleList []MapRule) *filter { // // Date : 11:58 2022/7/4 type filter struct { + jsonRaad abstract.IJsonRead + jsonWrite abstract.IJsonWrite sourceData string formatResult string filterRuleList []MapRule diff --git a/implement/gjson_read.go b/implement/gjson_read.go index 57e0c01..9ba9eb9 100644 --- a/implement/gjson_read.go +++ b/implement/gjson_read.go @@ -118,3 +118,9 @@ func (g *gjsonRead) ArrayWithReceiver(dataPath string, receiver any) error { } return serialize.JSON.UnmarshalWithNumber([]byte(strVal), receiver) } +func (g *gjsonRead) Value(dataPath string, dataType string, defaultValue any) (any, error) { + if len(dataType) == 0 { + dataType = g.Type(dataPath) + } + return gjson_hack.Value(consts.DataType(dataType), g.gjsonResult.Get(dataPath), defaultValue) +}