遇到带有未知键和复杂嵌套结构的 JSON 数据可能是一项艰巨的任务。考虑以下 JSON 格式:
{ "message": { "Server1.example.com": [ { "application": "Apache", "host": { "name": "/^Server-[13456]/" }, "owner": "User1", "project": "Web", "subowner": "User2" } ], "Server2.example.com": [ { "application": "Mysql", "host": { "name": "/^Server[23456]/" }, "owner": "User2", "project": "DB", "subowner": "User3" } ] }, "response_ms": 659, "success": true }
如此示例中所示,服务器名称 (Server[0-9].example.com) 不是预先确定的,并且可能会有所不同。此外,服务器名称后面的字段缺少显式键。
为了有效捕获此数据,我们可以使用 map[string]ServerStruct 结构:
type YourStruct struct { Success bool ResponseMS int Servers map[string]*ServerStruct } type ServerStruct struct { Application string Owner string [...] }
通过合并这些结构,我们可以将未知服务器名称分配到映射中。
为了进一步擅长解组 JSON,请考虑添加必要的 JSON 标签:
import "encoding/json" // YourStruct contains the JSON structure with success, response time, and a map of servers type YourStruct struct { Success bool ResponseMS int `json:"response_ms"` Servers map[string]*ServerStruct `json:"message"` } // ServerStruct holds server information, including application, owner, etc. type ServerStruct struct { Application string `json:"application"` Owner string `json:"owner"` [...] } // UnmarshalJSON is a custom unmarshaller that handles nesting and unknown keys func (s *YourStruct) UnmarshalJSON(data []byte) error { type YourStructHelper struct { Success bool ResponseMS int `json:"response_ms"` Servers map[string]ServerStruct `json:"message"` } var helper YourStructHelper if err := json.Unmarshal(data, &helper); err != nil { return err } s.Success = helper.Success s.ResponseMS = helper.ResponseMS s.Servers = make(map[string]*ServerStruct) for k, v := range helper.Servers { s.Servers[k] = &v // Explicitly allocate memory for each server } return nil }
通过这些调整,您可以有效地将提供的 JSON 解组到自定义结构中,为轻松的数据操作。
以上是如何解组带有未知键的嵌套 JSON?的详细内容。更多信息请关注PHP中文网其他相关文章!