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

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

问题描述:

I'm trying to generate JSON for a Terraform file. Because I (think I) want to use marshalling instead of rolling my own JSON, I'm using Terraforms JSON format instead of the 'native' TF format.

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

resource and aws_instance are static identifiers while web1 in this case is the random name. Also it wouldn't be unthinkable to also have web2 and web3.

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

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

The problem however; how do do I generate random/variable JSON keys with Go's field tags?

I have a feeling the answer is "You don't". What other alternatives do I have then?

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

  {
  “资源”:[
 {
“ aws_instance”:{
“ web1”:{
“ some”:“数据” 
} 
}] 
} 
  code>  pre  > 
 
 

resource code>和 aws_instance code>是静态标识符,而 web1 code>在此情况下是随机名称。 同样也有 web2 code>和 web3 code>也是不可思议的。 p>

  type资源结构{
 AwsResource AwsResource  `json:“ aws_instance,omitempty”`
} 
 
type AwsResource结构{
 AwsWebInstance AwsWebInstance`json:“ web1,omitempty”`
} 
  code>  pre> 
 
 这个问题;  如何使用Go的字段标签生成随机/可变的JSON密钥? strong>  p> 
 
 

我感觉答案是“您不要”。 我还有什么其他选择? p> div>

In most cases where there are names not known at compile time, a map can be used:

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
}

Here's an example showing how to construct the value for marshalling:

r := Resource{
    AWSInstance: map[string]AWSInstance{
        "web1": AWSInstance{
            AMI:   "qdx",
            Count: 2,
        },
    },
}

playground example