DEV Community

Cover image for How to pretty print json with golang ?
Mohamed Akrem Chabchoub
Mohamed Akrem Chabchoub

Posted on • Edited on

How to pretty print json with golang ?

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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"}]}

Enter fullscreen mode Exit fullscreen mode

After:

{
    "id": 1,
    "name": "John",
    "address": {
        "city": "New York",
        "zipcode": "10001"
    },
    "friends": [
        {
            "name": "Mike"
        },
        {
            "name": "Anna"
        }
    ]
}

Enter fullscreen mode Exit fullscreen mode

I hope this will help you, and thanks for reading.

Top comments (6)

Collapse
 
schemetastic profile image
Schemetastic (Rodrigo)

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. 😉

Collapse
 
m-a profile image
Mohamed Akrem Chabchoub

Thank you for your advice.

Collapse
 
stephencherry profile image
Stephen Olujare

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.

Collapse
 
theiyed profile image
Sebai Iyed

thank you for this helpful content

Collapse
 
m-a profile image
Mohamed Akrem Chabchoub

Thanks

Collapse
 
faroukabichou profile image
Farouk Abichou

Crazy Good Thanks for sharing