From 3c39a2674c5235da7184c32c975343ae4c233449 Mon Sep 17 00:00:00 2001 From: swchandrasekar Date: Mon, 23 Sep 2024 15:41:03 -0700 Subject: [PATCH] Add parseJSON template func Signed-off-by: swchandrasekar --- template/template.go | 6 ++++++ template/template_test.go | 13 ++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/template/template.go b/template/template.go index 92f8323e25..d591e3620f 100644 --- a/template/template.go +++ b/template/template.go @@ -15,6 +15,7 @@ package template import ( "bytes" + "encoding/json" tmplhtml "html/template" "io" "net/url" @@ -205,6 +206,11 @@ var DefaultFuncs = FuncMap{ } return t.In(loc), nil }, + "parseJSON": func(jsonStr string) (interface{}, error) { + var result interface{} + err := json.Unmarshal([]byte(jsonStr), &result) + return result, err + }, "since": time.Since, "humanizeDuration": commonTemplates.HumanizeDuration, } diff --git a/template/template_test.go b/template/template_test.go index ea8915b1af..e335114b38 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -561,7 +561,18 @@ func TestTemplateFuncs(t *testing.T) { in: "{{ . | since | humanizeDuration }}", data: time.Now().Add(-1 * time.Hour), exp: "1h 0m 0s", - }} { + }, + { + title: "Template using parseJSON - valid JSON", + in: `{{ $json := . | parseJSON }}{{ $json.key }}`, + data: `{"key": "value"}`, + exp: "value", + }, { + title: "Template using parseJSON - invalid JSON", + in: `{{ . | parseJSON }}`, + data: `{"key": "value"`, + expErr: "template: :1:7: executing \"\" at : error calling parseJSON: unexpected end of JSON input", + }} { tc := tc t.Run(tc.title, func(t *testing.T) { wg := sync.WaitGroup{}