我正在嘗試為Terraform 文件生成 JSON 。因為我(認為我)想使用編組而不是滾動我自己的 JSON,所以我使用 Terraforms JSON 格式而不是“本機”TF 格式。{ "resource": [ { "aws_instance": { "web1": { "some": "data" } }]}resource和aws_instance是靜態標識符,而web1在這種情況下是隨機名稱。此外,擁有web2and也不是不可想象的web3。type Resource struct { AwsResource AwsResource `json:"aws_instance,omitempty"`}type AwsResource struct { AwsWebInstance AwsWebInstance `json:"web1,omitempty"`}然而問題是;如何使用 Go 的字段標簽生成隨機/可變 JSON 密鑰?我有一種感覺,答案是“你沒有”。那我還有什么其他選擇?
1 回答

開滿天機
TA貢獻1786條經驗 獲得超13個贊
在大多數情況下,在編譯時存在未知名稱的情況下,可以使用映射:
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,
},
},
}
- 1 回答
- 0 關注
- 185 瀏覽
添加回答
舉報
0/150
提交
取消