[英]Marshal dynamic JSON field tags in Go
我正在嘗試為Terraform文件生成JSON。 因為(我想)我想使用編組而不是滾動自己的JSON,所以我使用Terraforms JSON格式而不是“本機” TF格式。
{
"resource": [
{
"aws_instance": {
"web1": {
"some": "data"
}
}]
}
resource
和aws_instance
是靜態標識符,而在這種情況下, web1
是隨機名稱。 同樣,擁有web2
和web3
也並非不可想象。
type Resource struct {
AwsResource AwsResource `json:"aws_instance,omitempty"`
}
type AwsResource struct {
AwsWebInstance AwsWebInstance `json:"web1,omitempty"`
}
但是,問題在於; 如何使用Go的字段標簽生成隨機/可變JSON密鑰?
我感覺答案是“您不”。 那我還有什么其他選擇?
在大多數情況下,在編譯時不知道名稱的情況下,可以使用映射:
type Resource struct {
AWSInstance map[string]AWSInstance `json:"aws_instance"`
}
type AWSInstance struct {
AMI string `json:"ami"`
Count int `json:"count"`
SourceDestCheck bool `json:"source_dest_check"`
// ... and so on
}
這是顯示如何構造編組值的示例:
r := Resource{
AWSInstance: map[string]AWSInstance{
"web1": AWSInstance{
AMI: "qdx",
Count: 2,
},
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.