1# Pretty
2
3[](https://pkg.go.dev/github.com/tidwall/pretty)
4
5Pretty is a Go package that provides [fast](#performance) methods for formatting JSON for human readability, or to compact JSON for smaller payloads.
6
7Getting Started
8===============
9
10## Installing
11
12To start using Pretty, install Go and run `go get`:
13
14```sh
15$ go get -u github.com/tidwall/pretty
16```
17
18This will retrieve the library.
19
20## Pretty
21
22Using this example:
23
24```json
25{"name": {"first":"Tom","last":"Anderson"}, "age":37,
26"children": ["Sara","Alex","Jack"],
27"fav.movie": "Deer Hunter", "friends": [
28 {"first": "Janet", "last": "Murphy", "age": 44}
29 ]}
30```
31
32The following code:
33```go
34result = pretty.Pretty(example)
35```
36
37Will format the json to:
38
39```json
40{
41 "name": {
42 "first": "Tom",
43 "last": "Anderson"
44 },
45 "age": 37,
46 "children": ["Sara", "Alex", "Jack"],
47 "fav.movie": "Deer Hunter",
48 "friends": [
49 {
50 "first": "Janet",
51 "last": "Murphy",
52 "age": 44
53 }
54 ]
55}
56```
57
58## Color
59
60Color will colorize the json for outputing to the screen.
61
62```go
63result = pretty.Color(json, nil)
64```
65
66Will add color to the result for printing to the terminal.
67The second param is used for a customizing the style, and passing nil will use the default `pretty.TerminalStyle`.
68
69## Ugly
70
71The following code:
72```go
73result = pretty.Ugly(example)
74```
75
76Will format the json to:
77
78```json
79{"name":{"first":"Tom","last":"Anderson"},"age":37,"children":["Sara","Alex","Jack"],"fav.movie":"Deer Hunter","friends":[{"first":"Janet","last":"Murphy","age":44}]}```
80```
81
82## Customized output
83
84There's a `PrettyOptions(json, opts)` function which allows for customizing the output with the following options:
85
86```go
87type Options struct {
88 // Width is an max column width for single line arrays
89 // Default is 80
90 Width int
91 // Prefix is a prefix for all lines
92 // Default is an empty string
93 Prefix string
94 // Indent is the nested indentation
95 // Default is two spaces
96 Indent string
97 // SortKeys will sort the keys alphabetically
98 // Default is false
99 SortKeys bool
100}
101```
102## Performance
103
104Benchmarks of Pretty alongside the builtin `encoding/json` Indent/Compact methods.
105```
106BenchmarkPretty-16 1000000 1034 ns/op 720 B/op 2 allocs/op
107BenchmarkPrettySortKeys-16 586797 1983 ns/op 2848 B/op 14 allocs/op
108BenchmarkUgly-16 4652365 254 ns/op 240 B/op 1 allocs/op
109BenchmarkUglyInPlace-16 6481233 183 ns/op 0 B/op 0 allocs/op
110BenchmarkJSONIndent-16 450654 2687 ns/op 1221 B/op 0 allocs/op
111BenchmarkJSONCompact-16 685111 1699 ns/op 442 B/op 0 allocs/op
112```
113
114*These benchmarks were run on a MacBook Pro 2.4 GHz 8-Core Intel Core i9.*
115
116## Contact
117Josh Baker [@tidwall](http://twitter.com/tidwall)
118
119## License
120
121Pretty source code is available under the MIT [License](/LICENSE).
122