Skip to content

Instantly share code, notes, and snippets.

@kjk
Created June 22, 2021 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjk/7fcba8b9910b41df5861f8906be07df9 to your computer and use it in GitHub Desktop.
Save kjk/7fcba8b9910b41df5861f8906be07df9 to your computer and use it in GitHub Desktop.
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