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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?