在Go中编组动态JSON字段标签 [英] Marshal dynamic JSON field tags in Go
问题描述
我正在尝试为 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"
}
}]
}
resource
和aws_instance
是静态标识符,而在这种情况下,web1
是随机名称.同时拥有web2
和web3
也不是不可思议的.
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屋!