我需要使用 Go 生成以下 JSON 输出。
{
"id": "zx222",
"links": {
"main_entity": {
"data": [{
"type": "car",
"id": "abc123"
}]
}
}
}
通过编码(marshal)处理生成上述 JSON 的直接方法是使用以下类型
type Element struct{
Id string `json:"id"`
Links LinksObject `json:"links"`
}
type LinksObject struct{
MainEntity MainEntityObject `json:"main_entity"`
}
type MainEntityObject struct{
Data []EntityDef `json:"data"`
}
type EntityDef struct{
Type string `json:"type"`
Id string `json:"id"`
}
是否有更好的方法来生成上述 JSON,而无需定义每个结构只是为了嵌套结构?
在问题背后添加一些我的想法。由于消息的包装方式,原始 JSON 具有额外的嵌套级别。但它们不一定具有任何意义,否则将它们定义为仅用于解码/编码为 JSON 的数据类型似乎没有必要。
最佳答案
type Element struct {
ID string `json:"id"`
Links struct {
MainEntity struct {
Data []struct {
Type string `json:"type"`
ID string `json:"id"`
} `json:"data"`
} `json:"main_entity"`
} `json:"links"`
}
关于json - 定义类型以生成嵌套 JSON 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60606915/