在Go中编组动态JSON字段标签

格本·雅各布斯:

我正在尝试为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,
        },
    },
}

游乐场的例子

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章