如何使golang打印JSON中的所有字段?

I'm still learning Go (coming from Python) and I'm trying to automate a task in AWS. I have this requirement at work that I need to write the JSON output to a file but I'm struggling how to print all the fields in my struct. I'm missing the Basket field.

I want it to be printed like this:

{
  "Basket": [
    {
      "Name": "Apple",
      "Color": "Red"
    },
    {
      "Name": "Banana",
      "Color": "Yellow"
    }
  ]
}

But I'm only getting this:

[
  {
    "Name": "Apple",
    "Color": "Red"
  },
  {
    "Name": "Banana",
    "Color": "Yellow"
  }
]

You can find my code here in Go Playground.

Put the fruit in a basket.

The difference between the expected output and actual output is that the array is wrapped with an object in the expected output. Modify the corresponding Go types to match the structure of the expected output.

var data = struct{ Basket []Fruit }{Basket: fruits}
dat, err := json.MarshalIndent(&data, "", "  ")

https://play.golang.org/p/7g9HDZ38XxU

Alternatively, change the existing Basket type to match the JSON and use that:

type Basket struct {
    Basket []Fruit
}

...

dat, err := json.MarshalIndent(&Basket{Basket:fruit}, "", "  ")

In your printJSON function you were just printing out the slide of fruits the basket. Creating and printing a basket struct and adding a JSON tag to the field Basket achieves what you want:

https://play.golang.org/p/aJcbP97CDGt

type Basket struct {
    Fruits []Fruit `json:"Basket"`
}

// Prints the output in JSON format.
func printJSON() {
    dat, err := json.MarshalIndent(Basket{fruits}, "", "  ")

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("This is printJSON().")
    fmt.Println(string(dat))
}