tidwall/pretty
GitHub: tidwall/pretty
一款高效的 Go 语言 JSON 美化与压缩库,提供格式化、终端着色和自定义输出等丰富选项。
Stars: 418 | Forks: 45
# Pretty
[](https://pkg.go.dev/github.com/tidwall/pretty)
# 快速入门
## 安装
要开始使用 Pretty,请安装 Go 并运行 `go get`:
```
$ go get -u github.com/tidwall/pretty
```
这将获取该库。
## Pretty
使用以下示例:
```
{"name": {"first":"Tom","last":"Anderson"}, "age":37,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter", "friends": [
{"first": "Janet", "last": "Murphy", "age": 44}
]}
```
以下代码:
```
result = pretty.Pretty(example)
```
会将 json 格式化为:
```
{
"name": {
"first": "Tom",
"last": "Anderson"
},
"age": 37,
"children": ["Sara", "Alex", "Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{
"first": "Janet",
"last": "Murphy",
"age": 44
}
]
}
```
## Color
Color 将为输出到屏幕的 json 着色。
```
result = pretty.Color(json, nil)
```
将会为结果添加颜色,以便打印到终端。
第二个参数用于自定义样式,传递 nil 将使用默认的 `pretty.TerminalStyle`。
## Ugly
以下代码:
```
result = pretty.Ugly(example)
```
会将 json 格式化为:
```
{"name":{"first":"Tom","last":"Anderson"},"age":37,"children":["Sara","Alex","Jack"],"fav.movie":"Deer Hunter","friends":[{"first":"Janet","last":"Murphy","age":44}]}```
```
## 自定义输出
有一个 `PrettyOptions(json, opts)` 函数,允许使用以下选项来自定义输出:
```
type Options struct {
// Width is an max column width for single line arrays
// Default is 80
Width int
// Prefix is a prefix for all lines
// Default is an empty string
Prefix string
// Indent is the nested indentation
// Default is two spaces
Indent string
// SortKeys will sort the keys alphabetically
// Default is false
SortKeys bool
}
```
## 性能
Pretty 与内置的 `encoding/json` Indent/Compact 方法的基准测试对比。
```
BenchmarkPretty-16 1000000 1034 ns/op 720 B/op 2 allocs/op
BenchmarkPrettySortKeys-16 586797 1983 ns/op 2848 B/op 14 allocs/op
BenchmarkUgly-16 4652365 254 ns/op 240 B/op 1 allocs/op
BenchmarkUglyInPlace-16 6481233 183 ns/op 0 B/op 0 allocs/op
BenchmarkJSONIndent-16 450654 2687 ns/op 1221 B/op 0 allocs/op
BenchmarkJSONCompact-16 685111 1699 ns/op 442 B/op 0 allocs/op
```
*这些基准测试是在 MacBook Pro 2.4 GHz 8 核 Intel Core i9 上运行的。*
## 联系方式
Josh Baker [@tidwall](http://twitter.com/tidwall)
## 许可证
Pretty 源代码基于 MIT [许可证](/LICENSE) 提供。
标签:EVTX分析, 日志审计