Skip to content

Commit

Permalink
Merge pull request #64 from md5/add-function-parse-json
Browse files Browse the repository at this point in the history
Add parseJson function
  • Loading branch information
jwilder committed Feb 27, 2015
2 parents d49c29c + 397e5c8 commit 9978084
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
9 changes: 9 additions & 0 deletions template.go
Expand Up @@ -216,6 +216,14 @@ func marshalJson(input interface{}) (string, error) {
return strings.TrimSuffix(buf.String(), "\n"), nil
}

func unmarshalJson(input string) (interface{}, error) {
var v interface{}
if err := json.Unmarshal([]byte(input), &v); err != nil {
return nil, err
}
return v, nil
}

// arrayFirst returns first item in the array or nil if the
// input is nil or empty
func arrayFirst(input interface{}) interface{} {
Expand Down Expand Up @@ -302,6 +310,7 @@ func newTemplate(name string) *template.Template {
"keys": keys,
"last": arrayLast,
"replace": strings.Replace,
"parseJson": unmarshalJson,
"sha1": hashSha1,
"split": strings.Split,
"trimPrefix": trimPrefix,
Expand Down
32 changes: 32 additions & 0 deletions template_test.go
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"testing"
"text/template"
Expand Down Expand Up @@ -518,6 +519,37 @@ func TestJson(t *testing.T) {
}
}

func TestParseJson(t *testing.T) {
tests := []struct {
tmpl string
context interface{}
expected string
}{
{`{{parseJson .}}`, `null`, `<no value>`},
{`{{parseJson .}}`, `true`, `true`},
{`{{parseJson .}}`, `1`, `1`},
{`{{parseJson .}}`, `0.5`, `0.5`},
{`{{index (parseJson .) "enabled"}}`, `{"enabled":true}`, `true`},
{`{{index (parseJson . | first) "enabled"}}`, `[{"enabled":true}]`, `true`},
}

for n, test := range tests {
tmplName := fmt.Sprintf("parseJson-test-%d", n)
tmpl := template.Must(newTemplate(tmplName).Parse(test.tmpl))

var b bytes.Buffer
err := tmpl.ExecuteTemplate(&b, tmplName, test.context)
if err != nil {
t.Fatalf("Error executing template: %v", err)
}

got := b.String()
if test.expected != got {
t.Fatalf("Incorrect output found; expected %s, got %s", test.expected, got)
}
}
}

func TestArrayClosestExact(t *testing.T) {
if arrayClosest([]string{"foo.bar.com", "bar.com"}, "foo.bar.com") != "foo.bar.com" {
t.Fatal("Expected foo.bar.com")
Expand Down

0 comments on commit 9978084

Please sign in to comment.