在 Go 中封送动态 JSON 字段标签

Ger*_*obs 2 json go terraform

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

{
  "resource": [
    {
      "aws_instance": {
        "web1": {
          "some": "data"
        }
    }]
}
Run Code Online (Sandbox Code Playgroud)

resourceaws_instance是静态标识符,而web1在这种情况下是随机名称。此外,拥有web2and也不是不可想象的web3

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

type AwsResource struct {
    AwsWebInstance AwsWebInstance `json:"web1,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

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

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

Cer*_*món 6

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

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
}
Run Code Online (Sandbox Code Playgroud)

下面是一个示例,展示了如何构造编组的值:

r := Resource{
    AWSInstance: map[string]AWSInstance{
        "web1": AWSInstance{
            AMI:   "qdx",
            Count: 2,
        },
    },
}
Run Code Online (Sandbox Code Playgroud)

游乐场示例