在 Go 中编组动态 JSON 字段标签 [英] Marshal dynamic JSON field tags in Go

查看:13
本文介绍了在 Go 中编组动态 JSON 字段标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Terraform 文件生成 JSON.因为我(想我)想使用编组而不是滚动我自己的 JSON,所以我使用 Terraforms JSON 格式而不是本机"TF 格式.

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"
        }
    }]
}

resourceaws_instance 是静态标识符,而 web1 在这种情况下是随机名称.同样拥有 web2web3 也不是不可想象的.

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"`
}

然而问题是;如何使用 Go 的字段标签生成随机/可变 JSON 密钥?

我感觉答案是你不知道".那我还有什么其他选择?

I have a feeling the answer is "You don't". What other alternatives do I have then?

推荐答案

在大多数情况下,在编译时存在未知名称的情况,可以使用映射:

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

游乐场示例

这篇关于在 Go 中编组动态 JSON 字段标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆