dongxuan2577 2015-07-21 13:38
浏览 76
已采纳

在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条回答 默认 最新

  • duangan6731 2015-07-21 14:01
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?