After I do
json, err := json.Marshal(buf)
I get something like:
{"a":123,"b":"abc"}
But what I want is an indented version of this:
{
"a": 123,
"b": "abc"
}
How?
The easiest way to do this is with MarshalIndent , which will let you specify how you would like it indented via the indent argument. Thus, json. MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.
JSON conventions¶ Format JSON files to be human readable. Use four spaces for indentation (matching OpenStack conventions used in Python and shell scripts). Do not use tab characters in the code, always use spaces. Use one space after the name-separator (colon).
JSON is a serialization format, not a presentation format. As such, there is no "standard" indentation - JSON is typically sent as compactly as possible.
Use json.MarshalIndent(group, "", "\t")
, try this:
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.MarshalIndent(group, "", "\t")
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}
output:
{
"ID": 1,
"Name": "Reds",
"Colors": [
"Crimson",
"Red",
"Ruby",
"Maroon"
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With