遇到帶有未知鍵和複雜嵌套結構的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中文網其他相關文章!