作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我仍在学习 Go(来自 Python)并且我正在尝试在 AWS 中自动执行任务。我在工作中有这个要求,我需要将 JSON 输出写入一个文件,但我正在努力如何打印我的结构中的所有字段。我缺少 Basket
字段。
我希望它打印成这样:
{
"Basket": [
{
"Name": "Apple",
"Color": "Red"
},
{
"Name": "Banana",
"Color": "Yellow"
}
]
}
但我只得到这个:
[
{
"Name": "Apple",
"Color": "Red"
},
{
"Name": "Banana",
"Color": "Yellow"
}
]
您可以在 Go Playground 中找到我的代码.
最佳答案
把水果放在篮子里。
预期输出与实际输出的区别在于,预期输出中数组被对象包裹。修改相应的 Go 类型以匹配预期输出的结构。
var data = struct{ Basket []Fruit }{Basket: fruits}
dat, err := json.MarshalIndent(&data, "", " ")
https://play.golang.org/p/7g9HDZ38XxU
或者,更改现有的 Basket
类型以匹配 JSON 并使用它:
type Basket struct {
Basket []Fruit
}
...
dat, err := json.MarshalIndent(&Basket{Basket:fruit}, "", " ")
关于json - 如何让golang打印出JSON中的所有字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855758/
我是一名优秀的程序员,十分优秀!