Skip to content

Commit

Permalink
Add parseJSON template func
Browse files Browse the repository at this point in the history
  • Loading branch information
swchandrasekar committed Sep 23, 2024
1 parent e149260 commit 6816703
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 6 additions & 0 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package template

import (
"bytes"
"encoding/json"
tmplhtml "html/template"
"io"
"net/url"
Expand Down Expand Up @@ -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,
}
Expand Down
13 changes: 12 additions & 1 deletion template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <parseJSON>: error calling parseJSON: unexpected end of JSON input",
}} {
tc := tc
t.Run(tc.title, func(t *testing.T) {
wg := sync.WaitGroup{}
Expand Down

0 comments on commit 6816703

Please sign in to comment.