Created
November 9, 2022 15:20
-
-
Save marvin/43fbeb2cb7fdba99d5c1cf1d5557372b to your computer and use it in GitHub Desktop.
golang json struct helper functions
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
// Prints objects into json pretty output | |
func PrettyStruct(data interface{}) (string, error) { | |
val, err := json.MarshalIndent(data, "", " ") | |
if err != nil { | |
return "", err | |
} | |
return string(val), nil | |
} | |
// pretty print coded byte in json format | |
func PrettyEncode(data interface{}, out io.Writer) error { | |
enc := json.NewEncoder(out) | |
enc.SetIndent("", " ") | |
if err := enc.Encode(data); err != nil { | |
return err | |
} | |
return nil | |
} | |
// example usage: | |
// printing a struct in json like format | |
res, err := PrettyStruct(mystruct) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(res) | |
// pretty print a []byte in json format | |
res, err := PrettyStruct(mybyte) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(res) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment