diff --git a/pkg/template/json/generator.go b/pkg/template/json/generator.go index ee5428ed8..3cc7f49e2 100644 --- a/pkg/template/json/generator.go +++ b/pkg/template/json/generator.go @@ -79,15 +79,15 @@ func (g *templateGenerator) generate(root templateNode) []templateSegment { } func (g *templateGenerator) generateObjectNode(node *objectNode, i int) bool { + if i == 0 { + g.buf.WriteByte('{') + } + if i >= len(node.members) { g.buf.WriteByte('}') return false } - if i == 0 { - g.buf.WriteByte('{') - } - mn := node.members[i] switch n := mn.value.(type) { case *jsonPathNode: @@ -114,15 +114,15 @@ func (g *templateGenerator) generateObjectNode(node *objectNode, i int) bool { } func (g *templateGenerator) generateArrayNode(node *arrayNode, i int) bool { + if i == 0 { + g.buf.WriteByte('[') + } + if i >= len(node.elements) { g.buf.WriteByte(']') return false } - if i == 0 { - g.buf.WriteByte('[') - } - en := node.elements[i] switch n := en.(type) { case *jsonPathNode: diff --git a/pkg/template/json/template_test.go b/pkg/template/json/template_test.go index 5c14c6893..8cfc302fe 100644 --- a/pkg/template/json/template_test.go +++ b/pkg/template/json/template_test.go @@ -27,6 +27,18 @@ import ( ) func TestTemplate_Execute(t *testing.T) { + Convey("empty array and empty object", t, func() { + model := map[string]interface{}{} + variables := map[string]interface{}{} + + tp, err := Compile(`[{"empty array":[],"empty object":{}}]`) + So(err, ShouldBeNil) + + v, err := tp.Execute(model, variables) + So(err, ShouldBeNil) + So(string(v), ShouldEqual, `[{"empty array":[],"empty object":{}}]`) + }) + Convey("refer variables", t, func() { model := map[string]interface{}{} variables := map[string]interface{}{}