簡體   English   中英

在Go中編組動態JSON字段標簽

[英]Marshal dynamic JSON field tags in Go

我正在嘗試為Terraform文件生成JSON。 因為(我想)我想使用編組而不是滾動自己的JSON,所以我使用Terraforms JSON格式而不是“本機” TF格式。

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

resourceaws_instance是靜態標識符,而在這種情況下, web1是隨機名稱。 同樣,擁有web2web3也並非不可想象。

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

游樂場的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM