JSON Nested Dynamic Structures Go Decoding
In this scenario, the JSON response contains dynamic keys within the nested "sms" object. Conventional struct decoding methods will fail due to the unknown phone numbers as keys.
Solution: Maps and Dynamic Key Handling
To effectively deserialize such data, a map data structure is employed. The amended code below introduces a map[string]SMSPhone to model the "sms" object:
type SMSPhone struct { Status string `json:"status"` StatusCode int `json:"status_code"` StatusText string `json:"status_text"` } type SMSSendJSON struct { Status string `json:"status"` StatusCode int `json:"status_code"` Sms map[string]SMSPhone `json:"sms"` Balance float64 `json:"balance"` }
Unmarshaling Process
With this map in place, the unmarshaling process can now correctly handle the dynamic phone numbers:
var result SMSSendJSON if err := json.Unmarshal([]byte(src), &result); err != nil { panic(err) }
Example Output
The result map will contain the phone numbers as keys and their associated SMSPhone structures:
{Status:OK StatusCode:100 Sms:map[79035671233:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения} 79105432212:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения} 79607891234:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения}] Balance:2676.18}
This approach allows for the efficient decoding of JSON responses with dynamic nested structures.
The above is the detailed content of How to Decode JSON with Dynamic Nested Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!