mark2web/pkg/filter/json.go
Sebastian Frank 0683e327c9
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
fixed pongo module version
2022-02-28 11:43:47 +01:00

36 lines
711 B
Go

package filter
import (
"encoding/json"
"strings"
"github.com/flosch/pongo2/v4"
)
// JSONFilter is a pongo2 filter, which returns a json string of the input
func JSONFilter(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
pretty := false
for _, s := range strings.Split(param.String(), ",") {
switch s {
case "pretty":
pretty = true
}
}
var err error
var jsonBytes []byte
if pretty {
jsonBytes, err = json.MarshalIndent(in.Interface(), "", " ")
} else {
jsonBytes, err = json.Marshal(in.Interface())
}
if err != nil {
return nil, &pongo2.Error{
Sender: "filter:json",
OrigError: err,
}
}
return pongo2.AsSafeValue(string(jsonBytes)), nil
}