Skip to content

Instantly share code, notes, and snippets.

@kjk
Created Jun 22, 2021
Embed
What would you like to do?
pretty print JSON (made with https://codeeval.dev)
package main
import (
"fmt"
"encoding/json"
"github.com/tidwall/pretty"
)
var prettyOpts = pretty.Options{
Width: 80,
Prefix: "",
Indent: " ",
// sorting keys only slightly slower
SortKeys: true,
}
// pretty-print if valid JSON. If not, return unchanged
// about 4x faster than naive version using json.Unmarshal() + json.Marshal()
func ppJSON(js []byte) []byte {
if !json.Valid(js) {
return js
}
return pretty.PrettyOptions(js, &prettyOpts)
}
func main() {
js := `{"requests": [
{ "id": "0a4da7d6-e93c-4ba8-a87c-c505e8bc81c8", "table": "block" }
]}`
res := ppJSON([]byte(js))
fmt.Printf("formatted JSON:\n%s\n", string(res))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment