diff --git a/examples/json/json-example b/examples/json/json-example index 3ad2628..ca00712 100644 --- a/examples/json/json-example +++ b/examples/json/json-example @@ -4,8 +4,8 @@ "name": "service1", "port": 8000 }, { - "name": "service2", - "port": 9000 + "name": "service2", + "port": 9000 } ] }` }} @@ -15,11 +15,15 @@ NAME1={{ jsonQuery $jsonDoc "services.[1].name" }} PORT1={{ jsonQuery $jsonDoc "services.[1].port" }} - {{ range $index, $value := jsonQuery $jsonDoc "services" }} + {{ $services := jsonQuery $jsonDoc "services" }} + + {{ range $index, $value := $services }} Index: {{ printf "%v" $index }} Name: {{ printf "%v" $value.name }} Port: {{ printf "%v" $value.port }} --- {{end}} + {{ json $services " " }} + {{end}} \ No newline at end of file diff --git a/template.go b/template.go index a42d15c..3a6d3d9 100644 --- a/template.go +++ b/template.go @@ -1,6 +1,7 @@ package main import ( + gojson "encoding/json" "fmt" "io/ioutil" "log" @@ -79,6 +80,25 @@ func isTrue(s string) bool { return false } +func json(data interface{}, args ...string) (string, error) { + prefix := "" + indent := " " + + if len(args) > 0 { + prefix = args[0] + } + + if len(args) > 1 { + indent = args[1] + } + + j, err := gojson.MarshalIndent(data, prefix, indent) + if err != nil { + return "", err + } + return string(j), err +} + func jsonQuery(jsonObj string, query string) (interface{}, error) { parser, err := gojq.NewStringQuery(jsonObj) if err != nil { @@ -128,6 +148,7 @@ func generateFile(templatePath, destPath string) bool { "isTrue": isTrue, "lower": strings.ToLower, "upper": strings.ToUpper, + "json": json, "jsonQuery": jsonQuery, "loop": loop, })