-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)) | ||
} |