Pretty Printing JSON on the Command Line with Go

Featured image for sharing metadata for article

As with other posts in this series, it's useful to be able to quickly convert a JSON string to a pretty-printed version.

In today's installment, we'll do it using Go.

Adapting the example from, we can use the json.Indent call to perform the coercion, reading stdin using io.ReadAll, resulting in the following:

package main

import (

func PrettyString(str []byte) (string, error) {
	var prettyJSON bytes.Buffer
	if err := json.Indent(&prettyJSON, str, "", "  "); err != nil {
		return "", err
	return prettyJSON.String(), nil

func main() {
	stdin, err := io.ReadAll(os.Stdin)
	if err != nil {

	res, err := PrettyString(stdin)
	if err != nil {
	fmt.Println(strings.TrimSuffix(res, "\n"))

This then allows us to convert:


To a pretty output:

go run main.go < file.json

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go #json #pretty-print.

Also on:

This post was filed under articles.

This post is part of the series pretty-print-json.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.