Today, we have a simple recipe to pretty-print JSON using Golang:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
)

func formatJSON(data []byte) ([]byte, error) {
    var out bytes.Buffer
    err := json.Indent(&out, data, "", "    ")
    if err == nil {
        return out.Bytes(), err
    }
    return data, nil
}

func main() {

    data := []byte(`{"key":"hello","msg":"world"}`)

    prettyJSON, err := formatJSON(data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(prettyJSON))

}

Run this in the Go Playground.

The idea is that we take a byte slice of JSON data and then use the json.Indent method to format it. It's signature is as follows:

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

To accomplish the same in Python, you can do:

import json

def formatJSON(input):
    parsed = json.loads(input)
    return json.dumps(parsed, indent=4)

def main():

    data = '{"key":"hello","msg":"world"}'

    pretty_json = formatJSON(data)

    print(pretty_json)

if __name__ == "__main__":
    main()

Related Posts

  • Looking up a CNAME in Go
  • Embedding file with Go 1.16
  • Parsing a key pair from a PEM file in Go
  • Gotcha with defer in Go
  • Truncating a Unix timestamp to the hour using Go