github.com/jaypipes/ghw@v0.21.1/pkg/marshal/marshal.go (about) 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 7 package marshal 8 9 import ( 10 "encoding/json" 11 12 "github.com/jaypipes/ghw/pkg/context" 13 yaml "gopkg.in/yaml.v3" 14 ) 15 16 // SafeYAML returns a string after marshalling the supplied parameter into YAML. 17 func SafeYAML(ctx *context.Context, p interface{}) string { 18 b, err := json.Marshal(p) 19 if err != nil { 20 ctx.Warn("error marshalling JSON: %s", err) 21 return "" 22 } 23 24 var jsonObj interface{} 25 if err := yaml.Unmarshal(b, &jsonObj); err != nil { 26 ctx.Warn("error converting JSON to YAML: %s", err) 27 return "" 28 } 29 30 yb, err := yaml.Marshal(jsonObj) 31 if err != nil { 32 ctx.Warn("error marshalling YAML: %s", err) 33 return "" 34 } 35 36 return string(yb) 37 } 38 39 // SafeJSON returns a string after marshalling the supplied parameter into 40 // JSON. Accepts an optional argument to trigger pretty/indented formatting of 41 // the JSON string. 42 func SafeJSON(ctx *context.Context, p interface{}, indent bool) string { 43 var b []byte 44 var err error 45 if !indent { 46 b, err = json.Marshal(p) 47 } else { 48 b, err = json.MarshalIndent(&p, "", " ") 49 } 50 if err != nil { 51 ctx.Warn("error marshalling JSON: %s", err) 52 return "" 53 } 54 return string(b) 55 }