I have a slice of structs, e.g:
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Countries []string
}
type Persons []Person
func main() {
persons := Persons{
Person{"a", 21, []string{"USA", "UK"}},
Person{"b", 30, []string{"Belgium", "Ireland"}},
Person{"c", 2, []string{"Canada"}},
}
b, _ := json.Marshal(persons)
//bIndented, _ := json.MarshalIndent(persons, "", " ")
fmt.Println("unindented")
fmt.Println(string(b))
fmt.Println()
//fmt.Println("indented")
//fmt.Println(string(bIndented))
}
Output:
unindented
[{"Name":"a","Age":21,"Countries":["USA","UK"]},{"Name":"b","Age":30,"Countries":["Belgium","Ireland"]},{"Name":"c","Age":2,"Countries":["Canada"]}]
Is there a way to get an output like below where each slice item is unindented but on a separate line:
[
{"Name":"a","Age":21,"Countries":["USA","UK"]},
{"Name":"b","Age":30,"Countries":["Belgium","Ireland"]},
{"Name":"c","Age":2,"Countries":["Canada"]}
]
This should be possible with custom json marshaller but would I need to make changes directly in the []byte
that's returned by json.Marshal
?