JSON Nested Dynamic Structures Go Decoding
Encounters often arise when working with JSON data that contains dynamic or unknown field names within nested structures. This can pose a challenge when attempting to accurately deserialize and process the data.
Example Data
Consider the following JSON data received after a server request:
{ "status": "OK", "status_code": 100, "sms": { "79607891234": { "status": "ERROR", "status_code": 203, "status_text": "Нет текста сообщения" }, "79035671233": { "status": "ERROR", "status_code": 203, "status_text": "Нет текста сообщения" }, "79105432212": { "status": "ERROR", "status_code": 203, "status_text": "Нет текста сообщения" } }, "balance": 2676.18 }
Custom Type Definitions
To handle this dynamic structure, custom type definitions can be employed:
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 []SMSPhone `json:"sms"` Balance float64 `json:"balance"` }
Using Maps
Since the sms object in the JSON has dynamic keys, it can be modeled using a map with the phone numbers as keys and the SMSPhone struct as the values:
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
With the custom types defined, the data can be unmarshaled as follows:
var result SMSSendJSON if err := json.Unmarshal([]byte(src), &result); err != nil { panic(err) } fmt.Printf("%+v", result)
This will result in a properly deserialized object with the dynamic phone numbers as keys in the result.Sms map.
Related Questions
The above is the detailed content of How to Decode JSON with Dynamic Nested Structures in Golang?. For more information, please follow other related articles on the PHP Chinese website!