英文:
Marshal dynamic JSON field tags in Go
问题
我正在尝试为Terraform文件生成JSON。因为我(认为我)想要使用编组而不是自己编写JSON,所以我使用了Terraform的JSON格式而不是“本机”的TF格式。
{
"resource": [
{
"aws_instance": {
"web1": {
"some": "data"
}
}
}
]
}
在这种情况下,resource
和aws_instance
是静态标识符,而web1
是随机名称。此外,也可以有web2
和web3
。
type Resource struct {
AwsResource AwsResource `json:"aws_instance,omitempty"`
}
type AwsResource struct {
AwsWebInstance AwsWebInstance `json:"web1,omitempty"`
}
然而,问题是:如何使用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
得分: 7
在大多数情况下,当存在在编译时不知道的名称时,可以使用映射(map):
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
}
下面是一个示例,展示了如何构建用于编组(marshalling)的值:
r := Resource{
AWSInstance: map[string]AWSInstance{
"web1": AWSInstance{
AMI: "qdx",
Count: 2,
},
},
}
英文:
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,
},
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论