From 493e238455b9c523948f518e165a5ca1d36db23d Mon Sep 17 00:00:00 2001 From: Sebastien Blot Date: Wed, 20 Apr 2022 09:49:32 +0200 Subject: [PATCH] poc JsonExtractSlice --- pkg/exprhelpers/exprlib.go | 1 + pkg/exprhelpers/jsonextract.go | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/pkg/exprhelpers/exprlib.go b/pkg/exprhelpers/exprlib.go index 768ec3834..1f8641fe6 100644 --- a/pkg/exprhelpers/exprlib.go +++ b/pkg/exprhelpers/exprlib.go @@ -44,6 +44,7 @@ func GetExprEnv(ctx map[string]interface{}) map[string]interface{} { "JsonExtract": JsonExtract, "JsonExtractUnescape": JsonExtractUnescape, "JsonExtractLib": JsonExtractLib, + "JsonExtractSlice": JsonExtractSlice, "File": File, "RegexpInFile": RegexpInFile, "Upper": Upper, diff --git a/pkg/exprhelpers/jsonextract.go b/pkg/exprhelpers/jsonextract.go index 1e3022df4..2ae85ea6f 100644 --- a/pkg/exprhelpers/jsonextract.go +++ b/pkg/exprhelpers/jsonextract.go @@ -1,6 +1,7 @@ package exprhelpers import ( + "encoding/json" "strings" "github.com/buger/jsonparser" @@ -58,3 +59,29 @@ func JsonExtract(jsblob string, target string) string { log.Tracef("extract path %+v", fullpath) return JsonExtractLib(jsblob, fullpath...) } + +func JsonExtractSlice(jsblob string, target string) []interface{} { + if !strings.HasPrefix(target, "[") { + target = strings.Replace(target, "[", ".[", -1) + } + fullpath := strings.Split(target, ".") + + log.Tracef("extract path %+v", fullpath) + bContent := JsonExtractLib(jsblob, fullpath...) + ret := make([]interface{}, 0) + json.Unmarshal([]byte(bContent), &ret) + return ret +} + +/*func JsonExtractMap(jsblob string, target string) map[string]interface{} { + if !strings.HasPrefix(target, "[") { + target = strings.Replace(target, "[", ".[", -1) + } + fullpath := strings.Split(target, ".") + + log.Tracef("extract path %+v", fullpath) + bContent := JsonExtractLib(jsblob, fullpath...) + ret := make(map[string]interface{}, 0) + json.Unmarshal([]byte(bContent), &ret) + return ret +}*/