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条)

报告相同问题?

悬赏问题

  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳