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

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

Marshal dynamic JSON field tags in Go

问题

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

  1. {
  2. "resource": [
  3. {
  4. "aws_instance": {
  5. "web1": {
  6. "some": "data"
  7. }
  8. }
  9. }
  10. ]
  11. }

在这种情况下,resourceaws_instance是静态标识符,而web1是随机名称。此外,也可以有web2web3

  1. type Resource struct {
  2. AwsResource AwsResource `json:"aws_instance,omitempty"`
  3. }
  4. type AwsResource struct {
  5. AwsWebInstance AwsWebInstance `json:"web1,omitempty"`
  6. }

然而,问题是:如何使用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.

  1. {
  2. "resource": [
  3. {
  4. "aws_instance": {
  5. "web1": {
  6. "some": "data"
  7. }
  8. }]
  9. }

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.

  1. type Resource struct {
  2. AwsResource AwsResource `json:"aws_instance,omitempty"`
  3. }
  4. type AwsResource struct {
  5. AwsWebInstance AwsWebInstance `json:"web1,omitempty"`
  6. }

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):

  1. type Resource struct {
  2. AWSInstance map[string]AWSInstance `json:"aws_instance"`
  3. }
  4. type AWSInstance struct {
  5. AMI string `json:"ami"`
  6. Count int `json:"count"`
  7. SourceDestCheck bool `json:"source_dest_check"`
  8. // ... and so on
  9. }

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

  1. r := Resource{
  2. AWSInstance: map[string]AWSInstance{
  3. "web1": AWSInstance{
  4. AMI: "qdx",
  5. Count: 2,
  6. },
  7. },
  8. }

playground 示例

英文:

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

  1. type Resource struct {
  2. AWSInstance map[string]AWSInstance `json:"aws_instance"`
  3. }
  4. type AWSInstance struct {
  5. AMI string `json:"ami"`
  6. Count int `json:"count"`
  7. SourceDestCheck bool `json:"source_dest_check"`
  8. // ... and so on
  9. }

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

  1. r := Resource{
  2. AWSInstance: map[string]AWSInstance{
  3. "web1": AWSInstance{
  4. AMI: "qdx",
  5. Count: 2,
  6. },
  7. },
  8. }

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:

确定