#development #golang #pattern #python
Today, we have a simple recipe to pretty-print JSON using Golang:
1package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "log"
8)
9
10func formatJSON(data []byte) ([]byte, error) {
11 var out bytes.Buffer
12 err := json.Indent(&out, data, "", " ")
13 if err == nil {
14 return out.Bytes(), err
15 }
16 return data, nil
17}
18
19func main() {
20
21 data := []byte(`{"key":"hello","msg":"world"}`)
22
23 prettyJSON, err := formatJSON(data)
24 if err != nil {
25 log.Fatal(err)
26 }
27
28 fmt.Println(string(prettyJSON))
29
30}
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:
1func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
Indent appends to
dst
an indented form of the JSON-encodedsrc
. Each element in a JSON object or array begins on a new, indented line beginning withprefix
followed by one or more copies ofindent
according to the indentation nesting. The data appended todst
does not begin with theprefix
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 ofsrc
are dropped, trailing space characters at the end ofsrc
are preserved and copied todst
. For example, ifsrc
has no trailing spaces, neither willdst
; ifsrc
ends in a trailing newline, so willdst
.
To accomplish the same in Python, you can do:
1import json
2
3def formatJSON(input):
4 parsed = json.loads(input)
5 return json.dumps(parsed, indent=4)
6
7def main():
8
9 data = '{"key":"hello","msg":"world"}'
10
11 pretty_json = formatJSON(data)
12
13 print(pretty_json)
14
15if __name__ == "__main__":
16 main()
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.