As you know by default in Go you will use fmt
to print json data, this is ok but the data will be not beuatiful in the terminal, take this util function to print your json data in a pretty format:
// PrettyPrintData takes a single argument 'data' of any type (interface{}).
func PrettyPrintData(data interface{}) {
// Convert data to pretty-printed JSON.
if prettyOutput, err := json.MarshalIndent(data, "", " "); err == nil {
fmt.Println(string(prettyOutput))
} else {
// Handle error
}
}
This is how it will look in the terminal:
Before:
{"id":1,"name":"John","address":{"city":"New York","zipcode":"10001"},"friends":[{"name":"Mike"},{"name":"Anna"}]}
After:
{
"id": 1,
"name": "John",
"address": {
"city": "New York",
"zipcode": "10001"
},
"friends": [
{
"name": "Mike"
},
{
"name": "Anna"
}
]
}
I hope this will help you, and thanks for reading.
Top comments (6)
Hello!
Your post seems very useful. To improve it a little, do you think you could share a sample of how JSON data does look with
fmt
and compare it with the util function you shared?And by the way, welcome to the DEV Community. I hope I can see more Go posts from you in the future! You know what? I'll follow you. 😉
Thank you for your advice.
Hello SoftDev434,
I must confess your headline seems interest but when i check the post it seems straight forward too but i am curious why you did not share a smaple out here. That way i will have consider if its pretty or not! Meanwhile, I think Logrus print output to console in a pretty way too. You might want to look into that as well.
Thank you for sharing though. I will follow you.
thank you for this helpful content
Thanks
Crazy Good Thanks for sharing