Unmarshalling Nested JSON with Unknown Keys
The challenge lies in parsing a JSON structure with an unknown number of outer keys and a confusingly structured nested key. Consider the following JSON format:
{ "message": { "Server1.example.com": [], "Server2.example.com": [] }, "response_ms": 659, "success": true }
Struct Definition Complications
The complexity stems from the absence of a clear key outside the server name and the dynamic nature of the outer keys. The initial attempt using a deeply nested struct:
type ServerDetails struct { Message struct { Hostname struct { Details struct { Application string `json:"application"` } `json:"-"` } `json:"-"` } `json:"message"` }
fails due to the unknown server names and the single nested key without an outer key.
Dynamic Key Solution
To overcome these challenges, one can utilize a map[string]ServerStruct within the top-level struct. ServerStruct contains application, owner, and other relevant information specific to each server. JSON tags can be strategically added to ensure proper parsing.
Revised Struct Definition
type YourStruct struct { Success bool ResponseMS int Servers map[string]*ServerStruct } type ServerStruct struct { Application string Owner string [...] }
JSON Tags and Unmarshalling
Additional JSON tags are necessary:
{ "message": { "Server1.example.com": [ { "application": "Apache", "host": { "name": "/^Server-[13456]/" }, "owner": "User1", "project": "Web", "subowner": "User2" } ],
The "message" field now unmarshals into a map[string][]ServerStruct. Each key in the map represents a server name, and the corresponding value is an array of ServerStruct. The "host" field is ignored during unmarshalling using the "-" tag.
With these modifications, the JSON data can be successfully parsed into the revised struct.
The above is the detailed content of How to Unmarshall Nested JSON with Unknown Keys and Dynamic Server Names?. For more information, please follow other related articles on the PHP Chinese website!