drmgg4411
2019-02-24 19:39
浏览 354

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

图片转代码服务由CSDN问答提供 功能建议

我仍在学习Go(来自Python),并且正在尝试在AWS中自动执行任务。 我在工作时有这个要求,我需要将JSON输出写入文件,但是我正在努力如何打印结构中的所有字段。 我缺少<购物篮>字段。

我希望这样打印:

  {  
“购物篮”:[
 {
“名称”:“ Apple”,
“颜色”:“红色” 
},
 {
“名称”:“香蕉”,
“颜色 “:”黄色“ 
} 
] 
} 
   
 
 

但是我只得到这个:

   [
 {
“名称”:“苹果”,
“颜色”:“红色” 
},
 {
“名称”:“香蕉”,
“颜色”:“ 黄色“ 
} 
] 
   
 
 

您可以在去游乐场

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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}, "", "  ")
    
    点赞 打赏 评论
  • duanmao1319 2019-02-24 20:09

    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))
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题