Skip to content

Commit 9978084

Browse files
committed
Merge pull request #64 from md5/add-function-parse-json
Add parseJson function
2 parents d49c29c + 397e5c8 commit 9978084

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

template.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,14 @@ func marshalJson(input interface{}) (string, error) {
216216
return strings.TrimSuffix(buf.String(), "\n"), nil
217217
}
218218

219+
func unmarshalJson(input string) (interface{}, error) {
220+
var v interface{}
221+
if err := json.Unmarshal([]byte(input), &v); err != nil {
222+
return nil, err
223+
}
224+
return v, nil
225+
}
226+
219227
// arrayFirst returns first item in the array or nil if the
220228
// input is nil or empty
221229
func arrayFirst(input interface{}) interface{} {
@@ -302,6 +310,7 @@ func newTemplate(name string) *template.Template {
302310
"keys": keys,
303311
"last": arrayLast,
304312
"replace": strings.Replace,
313+
"parseJson": unmarshalJson,
305314
"sha1": hashSha1,
306315
"split": strings.Split,
307316
"trimPrefix": trimPrefix,

template_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"bytes"
55
"encoding/json"
6+
"fmt"
67
"reflect"
78
"testing"
89
"text/template"
@@ -518,6 +519,37 @@ func TestJson(t *testing.T) {
518519
}
519520
}
520521

522+
func TestParseJson(t *testing.T) {
523+
tests := []struct {
524+
tmpl string
525+
context interface{}
526+
expected string
527+
}{
528+
{`{{parseJson .}}`, `null`, `<no value>`},
529+
{`{{parseJson .}}`, `true`, `true`},
530+
{`{{parseJson .}}`, `1`, `1`},
531+
{`{{parseJson .}}`, `0.5`, `0.5`},
532+
{`{{index (parseJson .) "enabled"}}`, `{"enabled":true}`, `true`},
533+
{`{{index (parseJson . | first) "enabled"}}`, `[{"enabled":true}]`, `true`},
534+
}
535+
536+
for n, test := range tests {
537+
tmplName := fmt.Sprintf("parseJson-test-%d", n)
538+
tmpl := template.Must(newTemplate(tmplName).Parse(test.tmpl))
539+
540+
var b bytes.Buffer
541+
err := tmpl.ExecuteTemplate(&b, tmplName, test.context)
542+
if err != nil {
543+
t.Fatalf("Error executing template: %v", err)
544+
}
545+
546+
got := b.String()
547+
if test.expected != got {
548+
t.Fatalf("Incorrect output found; expected %s, got %s", test.expected, got)
549+
}
550+
}
551+
}
552+
521553
func TestArrayClosestExact(t *testing.T) {
522554
if arrayClosest([]string{"foo.bar.com", "bar.com"}, "foo.bar.com") != "foo.bar.com" {
523555
t.Fatal("Expected foo.bar.com")

0 commit comments

Comments
 (0)