0

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?

Junaid
  • 3,477
  • 1
  • 24
  • 24
  • 1
    You can even do better - https://go.dev/play/p/ZGMvDMkK0TU – Inian Jul 20 '22 at 18:43
  • It's sounds like the OP wanted compact element rendering & pretty list rendering - so this would require a customer marshaller for the desired type. – colm.anseo Jul 20 '22 at 23:38
  • @colm.anseo I'm not sure how to achieve cleanly this with a custom marshaller, so want to understand if anyone has done something similar. – Junaid Jul 21 '22 at 14:44
  • @Inian I'm aware of the `json.MarshalIndent` function, but I have a bit different requirement for the output. – Junaid Jul 21 '22 at 14:45

0 Answers0