我们如何在golang中的struct中初始化struct类型的数组(用于存储json输出)
I need to initialize the following data structure which will store a json. The Attack_plans will hold multiple plans and if I loop through the GeneratePlan struct, I need all the plans that were stored.
type GeneratePlan struct {
Mode string `json:"mode"`
Name string `json:"name"`
Schema string `json:"schema"`
Version string `json:"version"`
Attack_plans []struct {
Attack_plan *Attack_plan `json:"attack-plan"`
} `json:"attack-plans"`
}
type Attack_plan struct {
Attack_resources []struct {
Attack_resource *Attack_resource `json:"attack-resource"`
} `json:"attack-resources"`
}
Can anyone please suggest something? If the data structure needs to be simplified before initializing it, then please suggest that as well. I am very new to golang so please ignore the best practices to follow. Any help is appreciated. Thanks!
我需要初始化以下将存储json的数据结构。 Attack_plans将包含多个计划,如果我遍历GeneratePlan结构,则需要存储的所有计划。 p>
type GeneratePlan结构{
模式字符串`json:“ 模式“`
名称字符串`json:” name“`
模式字符串`json:” schema“`
版本字符串`json:” version“`
Attack_plans [] struct {
Attack_plan * Attack_plan`json :“”攻击计划“`
}`json:”攻击计划“`
}
type Attack_plan struct {
Attack_resources [] struct {
Attack_resource * Attack_resource`json:” attack-resource“`
}`json:“攻击资源”`
}
code> pre>
有人可以提出建议吗? 如果在初始化之前需要简化数据结构,则也建议这样做。 我刚接触过golang,因此请忽略要遵循的最佳做法。 任何帮助表示赞赏。 谢谢! p>
div>
I found the solution! This simplifies the above data structure!
type GeneratePlan struct{
Mode string `json:"mode"`
Name string `json:"name"`
Schema string `json:"schema"`
Version string `json:"version"`
Attack_plans []struct1 `json:"attack-plans"`
}
type struct1 struct {
Attack_plan Attack_plan `json:"attack-plan"`
}
type Attack_plan struct{
Attack_resouces []struct2 `json:"attack-resources"`
}
type struct2 struct {
Attack_resource Attack_resource `json:"attack-resource"`
}
why don't u just json.marshal your object to a json string, you can got answer
generatePlan := GeneratePlan{
Mode: "mode",
Name: "name",
Schema: "sachema",
Version: "version",
Attack_plans: []struct {
Attack_plan *Attack_plan `json:"attack-plan"`
}{
{Attack_plan: &Attack_plan{[]struct {
Attack_resource *Attack_resource `json:"attack-resource"`
}{
{Attack_resource: new(Attack_resource)},
{Attack_resource: new(Attack_resource)},
}}},
{Attack_plan: &Attack_plan{[]struct {
Attack_resource *Attack_resource `json:"attack-resource"`
}{
{Attack_resource: new(Attack_resource)},
{Attack_resource: new(Attack_resource)},
}}},
},
}