在Go语言中,如何编组动态的JSON字段标签?

huangapple go评论79阅读模式
英文:

Marshal dynamic JSON field tags in Go

问题

我正在尝试为Terraform文件生成JSON。因为我(认为我)想要使用编组而不是自己编写JSON,所以我使用了Terraform的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键?

我有一种感觉,答案是“你不能”。那么我还有哪些其他选择呢?

英文:

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?

答案1

得分: 7

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

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
}

下面是一个示例,展示了如何构建用于编组(marshalling)的值:

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

playground 示例

英文:

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

huangapple
  • 本文由 发表于 2015年7月21日 21:38:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/31540705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定