Pretty Printing JSON Output in Go with Built-in Functions
When dealing with JSON output in Go programs, it's often desirable to make it human readable. While jq can be used for this purpose, there are also built-in functions within the Go standard library that can achieve the desired result.
Json Marshal Indenting
The encoding/json package provides the json.MarshalIndent() function for pretty printing JSON output. It takes two additional parameters:
By passing an empty string as the prefix and a space as the indent, you can obtain human readable JSON output:
m := map[string]interface{}{"id": "uuid1", "name": "John Smith"} data, err := json.MarshalIndent(m, "", " ") if err != nil { panic(err) } fmt.Println(string(data))
Output:
{ "id": "uuid1", "name": "John Smith" } { "id": "uuid1", "name": "John Smith" }
You can also use the json.Encoder.SetIndent() method to set the indentation parameters when using an Encoder:
enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") if err := enc.Encode(m); err != nil { panic(err) }
Json Indenting
If you already have a JSON string, you can use the json.Indent() function to format it:
src := `{"id":"uuid1","name":"John Smith"}` dst := &bytes.Buffer{} if err := json.Indent(dst, []byte(src), "", " "); err != nil { panic(err) } fmt.Println(dst.String())
Output:
{ "id": "uuid1", "name": "John Smith" }
The above is the detailed content of How to Pretty Print JSON Output in Go Using Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!