Skip to content

Instantly share code, notes, and snippets.

@baijum
Last active October 14, 2020 03:26
Show Gist options
  • Select an option

  • Save baijum/4089a736b957a79c508e81ff5eee2824 to your computer and use it in GitHub Desktop.

Select an option

Save baijum/4089a736b957a79c508e81ff5eee2824 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"os"
"text/template"
"github.com/PaesslerAG/jsonpath"
)
func jsonPath(m interface{}, q string) (string, error) {
v := interface{}(nil)
err := json.Unmarshal([]byte(m.(string)), &v)
if err != nil {
return "", err
}
out, err := jsonpath.Get(q, v)
if err != nil {
return "", err
}
return out.(string), nil
}
func main() {
t := template.Must(template.New("letter").Funcs(template.FuncMap{"jsonp": jsonPath}).Parse(`{{ jsonp . "$.username" }}`))
err := t.Execute(os.Stdout, `{"username": "guest", "password": "secret"}`)
if err != nil {
fmt.Println("executing template:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment