Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parseJSON template func #4035

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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