Pretty is a high-performance Go package for formatting JSON with flexible pretty-printing capabilities, featuring customizable indentation and depth control.
- 🚀 High Performance - Optimized with
fastjsonandbytebufferpoolfor minimal memory allocation - 🎨 Flexible Formatting - Configurable indentation styles and depth control
- ⚙️ Multiple Input Types - Supports
[]byte,string,*fastjson.Value, and any JSON-serializable Go value - 📏 Depth Control - Configurable max/min expansion depth
- 🔄 Dual Output Modes - Pretty-printed (Format) and compact (Ugly) output
go get -u github.com/zc310/pretty{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [
"Catherine",
"Thomas",
"Trevor"
],
"spouse": null
}The following code:
result = pretty.Format(example)Will format the json to:
{
"firstName":"John",
"lastName":"Smith",
"isAlive":true,
"age":27,
"address":{"streetAddress":"21 2nd Street","city":"New York","state":"NY","postalCode":"10021-3100"},
"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],
"children":["Catherine","Thomas","Trevor"],
"spouse":null
}package main
import (
"fmt"
"github.com/zc310/pretty"
)
func main() {
jsonStr := `{"name":"John","age":30,"address":{"city":"New York","zip":"10001"}}`
// Default formatting
fmt.Println(string(pretty.Format(jsonStr)))
// Compact output
fmt.Println(string(pretty.Ugly(jsonStr)))
// Custom options
opts := &pretty.Options{
Indent: " ", // 4-space indent
MaxDepth: 2, // Max expansion depth
}
fmt.Println(string(pretty.FormatOptions(jsonStr, opts)))
}// Format directly from Go values
data := map[string]interface{}{
"name": "Alice",
"skills": []string{"Go", "JavaScript", "Python"},
}
fmt.Println(string(pretty.Format(data)))
// Handle fastjson.Value
val, _ := fastjson.Parse(`{"key":"value"}`)
fmt.Println(string(pretty.Format(val)))type Options struct {
Indent string // Indentation string (default: two spaces)
MaxDepth int // Maximum expansion depth (0 = unlimited)
MinDepth int // Minimum expansion depth (0 = unlimited)
}Format(o any) []byte- Format with default optionsUgly(o any) []byte- Compact output (no formatting)FormatOptions(o any, opts *Options) []byte- Format with custom options
- Buffer Pool Management - Uses
bytebufferpoolto reduce memory allocations - Zero-Copy Processing - Directly operates on raw JSON bytes
- Optimized Depth Calculation - Efficient nested depth computation
- Minimal String Operations - Avoids unnecessary string conversions and concatenations