Skip to content

Instantly share code, notes, and snippets.

@tehmoon
Last active April 27, 2018 18:43
Show Gist options
  • Save tehmoon/2f0ca396a6662e837d1c11a6adbc3b91 to your computer and use it in GitHub Desktop.
Save tehmoon/2f0ca396a6662e837d1c11a6adbc3b91 to your computer and use it in GitHub Desktop.
Using Go templating engine with JSON
package main
import (
"encoding/json"
"os"
"text/template"
)
var data = map[string]interface{}{
"blih": true,
"blah": map[string]interface{}{
"bluh": "false",
},
"bloh": []int{1,2,3,4,5},
}
var jsonFunc = template.FuncMap{
"json": func(d interface{}) string {
payload, err := json.Marshal(d)
if err != nil {
return ""
}
return string(payload[:])
},
"json_indent": func(d interface{}) (string) {
payload, err := json.MarshalIndent(d, "", " ")
if err != nil {
return ""
}
return string(payload[:])
},
"newline": func() (string) {
return "\n"
},
}
func main() {
tmpl, err := template.New("test").Funcs(jsonFunc).Parse("{{json . | js}}")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment