drmgg4411 2019-02-24 19:39
浏览 656
已采纳

如何使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.

  • 写回答

2条回答 默认 最新

  • drza10046 2019-02-24 20:04
    关注

    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}, "", "  ")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?