英文:
Object inside slice in Go
问题
我正在尝试将多个对象嵌入到一个切片中,以便稍后将它们导出为JSON。JSON应该类似于这样:
[
{
"name": "Nginx",
"version": "1.9"
},
{
"name": "ircd-hybrid",
"version": "8.2"
}
]
到目前为止,我在Go中有以下结构体:
type response struct {
application []struct {
name string
version string
}
}
现在(我甚至不确定结构体是否正确),我尝试以这种方式访问它(同样,不确定是否正确):
var d response
d.application[0].name = "Nginx"
d.application[0].version = "1.9"
依此类推。然而,它没有起作用,所以我猜我在某个地方出错了。我只是不知道具体在哪里。
英文:
I am trying to embed multiple objects inside a slice, so I can later export them as JSON. The JSON should look something like this:
[
{
name: "Nginx"
version: "1.9"
},
{
name: ircd-hybrid"
version: "8.2"
}
]
So far I have this struct in Go:
type response struct {
application []struct {
name string
version string
}
}
Now (I'm not even sure if the struct is correct), I'm trying to access it this way (again, not sure if this is correct):
var d response
d[0].name = "Nginx"
d[0].version = "1.9"
And so on and so forth. However, it is not working, so I assume I went wrong somewhere. I just don't know where.
答案1
得分: 0
你的'model'的形式(在这种情况下是Go中的结构体)不太对。你真正想要的是这样的:
type application struct {
Name string `json:"name"` // 需要将这些首字母大写,这样才能导出
Version string `json:"version"` // 否则无法进行编组
}
apps := []application{
{Name: "Windows", Version: "10"},
}
app := application{Name: "Linux", Version: "14.2"}
apps = append(apps, app)
JSON以[
开头,表示它只是一个数组,没有封闭的对象。如果有的话,你需要另一个类型,其中包含一个[]application
类型的属性。要向该数组添加项,可以使用append
函数或使用“复合字面量”语法初始化它。
编辑:我添加了一些注释,以便生成的JSON具有像你的示例中那样的小写名称。如果在Go中未导出属性,其他库(如encoding/json
)将无法使用它。
英文:
The form of your 'model' (the struct in Go in this case) isn't quite right. You really just want this;
type application struct {
Name string `json:"name"` // gotta uppercase these so they're exported
Version string `json:"version"` // otherwise you can't marshal them
}
apps := []application{
application{Name:"Windows", Version:"10"}
}
app := application{Name:"Linux", Vesion:"14.2"}
apps = append(apps, app)
The json opens with [
meaning it is just an array, there is no enclosing object. If there were you would want another type with an application array ( []application
) property. To add items to that array you can use append
or initialize it with some instance using the 'composite literal' syntax.
EDIT: I added some annotations so the json produced will have lower cased names like in your example. If a property isn't exported in Go other libraries like encoding/json
won't be able to use it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论