3

我正在尝试为Terraform 文件生成 JSON 。因为我(想我)想使用编组而不是滚动我自己的 JSON,所以我使用 Terraforms JSON 格式而不是“本机”TF 格式。

{
  "resource": [
    {
      "aws_instance": {
        "web1": {
          "some": "data"
        }
    }]
}

resource并且aws_instance是静态标识符,而web1在这种情况下是随机名称。web2此外,拥有and也不是不可想象的web3

type Resource struct {
    AwsResource AwsResource `json:"aws_instance,omitempty"`
}

type AwsResource struct {
    AwsWebInstance AwsWebInstance `json:"web1,omitempty"`
}

然而问题是;如何使用 Go 的字段标签生成随机/可变 JSON 键?

我感觉答案是“你没有”。那我还有什么其他选择?

4

1 回答 1

7

在大多数情况下,在编译时不知道名称的情况下,可以使用映射:

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,
        },
    },
}

游乐场示例

于 2015-07-21T14:01:11.467 回答