Skip to content

Commit

Permalink
Add decodeJSON as a templating option
Browse files Browse the repository at this point in the history
With this change you can parse a string as JSON, to get at the values.
  • Loading branch information
bittersweet committed Nov 4, 2016
1 parent 57d0ab2 commit bef4dac
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
18 changes: 15 additions & 3 deletions notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package main

import (
"bytes"
"encoding/json"
"log"
"reflect"
"text/template"

Expand Down Expand Up @@ -80,6 +82,15 @@ func present(str interface{}) bool {
return true
}

func decodeJSON(str string) map[string]interface{} {
var parsed map[string]interface{}
err := json.Unmarshal([]byte(str), &parsed)
if err != nil {
log.Fatal("json.Unmarshal decodeJson", err)
}
return parsed
}

func eq(x, y interface{}) bool {
normalize := func(v interface{}) interface{} {
vv := reflect.ValueOf(v)
Expand All @@ -100,9 +111,10 @@ func eq(x, y interface{}) bool {
}

var funcMap = template.FuncMap{
"isset": isset,
"present": present,
"eq": eq,
"isset": isset,
"present": present,
"eq": eq,
"decodeJSON": decodeJSON,
}

func (n *Notifier) renderTemplate(e *Event) ([]byte, error) {
Expand Down
15 changes: 15 additions & 0 deletions notifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,18 @@ func TestEq(t *testing.T) {
assert.True(t, eq(data["a"], "string"))
assert.False(t, eq(data["a"], "something else"))
}

func TestDecodeJSON(t *testing.T) {
n := Notifier{
EventName: "User",
Template: "nested: {{ $obj := decodeJSON .nested }}{{ $obj.key }}",
NotificationType: "email",
}

data := types.JSONText(`{"nested": "{\"key\": \"value\"}"}`)
event := setupTestNotifier(data)

result, _ := n.renderTemplate(&event)
expected := []byte("nested: value")
assert.Equal(t, expected, result)
}

0 comments on commit bef4dac

Please sign in to comment.