Created
June 22, 2021 02:27
-
-
Save kjk/7fcba8b9910b41df5861f8906be07df9 to your computer and use it in GitHub Desktop.
pretty print JSON (made with https://codeeval.dev)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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