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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大