prettify/main.go

56 lines
1.0 KiB
Go
Raw Normal View History

2020-05-10 13:36:48 +00:00
package prettify
import (
"encoding/json"
"fmt"
"github.com/TylerBrock/colorjson"
)
2020-05-10 14:03:39 +00:00
// Print will beautify the output of body
2020-05-10 13:38:17 +00:00
func Print(body interface{}) {
2020-05-10 13:36:48 +00:00
b, err := json.Marshal(body)
2020-10-14 14:23:50 +00:00
if err != nil {
panic(err)
}
2020-05-10 13:36:48 +00:00
var obj map[string]interface{}
json.Unmarshal(b, &obj)
// Make a custom formatter with indent set
f := colorjson.NewFormatter()
f.Indent = 2
2020-10-14 14:23:50 +00:00
// Marshal the Colorized JSON
2020-05-10 13:36:48 +00:00
s, err := f.Marshal(obj)
if err != nil {
panic(err)
}
2020-08-03 19:45:34 +00:00
// Print out string to stdout
2020-05-10 13:36:48 +00:00
fmt.Println(string(s))
}
// PrintArray will beautify the output of an interface array (bodyArray)
2020-10-14 14:23:50 +00:00
func PrintArray(bodyArray interface{}) {
b, err := json.Marshal(bodyArray)
if err != nil {
panic(err)
}
2020-10-14 14:23:50 +00:00
var obj []map[string]interface{}
json.Unmarshal(b, &obj)
// Make a custom formatter with indent set
f := colorjson.NewFormatter()
f.Indent = 2
for i := range obj {
// Marshal the Colorized JSON
s, err := f.Marshal(obj[i])
if err != nil {
panic(err)
}
// Print out string to stdout
fmt.Println(string(s))
}
}