marshal.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // Use and distribution licensed under the Apache license version 2.
  3. //
  4. // See the COPYING file in the root project directory for full text.
  5. //
  6. package marshal
  7. import (
  8. "encoding/json"
  9. "github.com/ghodss/yaml"
  10. "github.com/jaypipes/ghw/pkg/context"
  11. )
  12. // safeYAML returns a string after marshalling the supplied parameter into YAML
  13. func SafeYAML(ctx *context.Context, p interface{}) string {
  14. b, err := json.Marshal(p)
  15. if err != nil {
  16. ctx.Warn("error marshalling JSON: %s", err)
  17. return ""
  18. }
  19. yb, err := yaml.JSONToYAML(b)
  20. if err != nil {
  21. ctx.Warn("error converting JSON to YAML: %s", err)
  22. return ""
  23. }
  24. return string(yb)
  25. }
  26. // safeJSON returns a string after marshalling the supplied parameter into
  27. // JSON. Accepts an optional argument to trigger pretty/indented formatting of
  28. // the JSON string
  29. func SafeJSON(ctx *context.Context, p interface{}, indent bool) string {
  30. var b []byte
  31. var err error
  32. if !indent {
  33. b, err = json.Marshal(p)
  34. } else {
  35. b, err = json.MarshalIndent(&p, "", " ")
  36. }
  37. if err != nil {
  38. ctx.Warn("error marshalling JSON: %s", err)
  39. return ""
  40. }
  41. return string(b)
  42. }