From 8920f571470a3442bc6791f70e320af7e7a24473 Mon Sep 17 00:00:00 2001 From: Erik Unger Date: Thu, 10 Aug 2023 15:00:18 +0200 Subject: [PATCH] added PrintAsJSON --- printjson.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 printjson.go diff --git a/printjson.go b/printjson.go new file mode 100644 index 0000000..76cadec --- /dev/null +++ b/printjson.go @@ -0,0 +1,32 @@ +package pretty + +import ( + "encoding/json" + "fmt" + "strings" +) + +// PrintAsJSON marshalles input as indented JSON +// and calles fmt.Println with the result. +// If indent arguments are given, they are joined into +// a string and used as JSON line indent. +// If no indet argument is given, two spaces will be used +// to indent JSON lines. +// A byte slice as input will be marshalled as json.RawMessage. +func PrintAsJSON(input interface{}, indent ...string) { + var indentStr string + if len(indent) == 0 { + indentStr = " " + } else { + indentStr = strings.Join(indent, "") + } + if b, ok := input.([]byte); ok { + input = json.RawMessage(b) + } + data, err := json.MarshalIndent(input, "", indentStr) + if err != nil { + _, _ = fmt.Println(fmt.Errorf("%w from input: %#v", err, input)) + return + } + _, _ = fmt.Println(string(data)) +}