Go Decoding of JSON Nested Dynamic Structures
This discussion explores the challenge of parsing JSON data with nested dynamic structures in Go.
Problem:
Sample JSON data contains a nested structure with dynamic keys, such as phone numbers, as seen below:
{ "status": "OK", "status_code": 100, "sms": { "79607891234": { "status": "ERROR", "status_code": 203, "status_text": "Нет текста сообщения" }, "79035671233": {...}, "79105432212": {...} }, "balance": 2676.18 }
The provided sample code attempts to use a fixed list of phone numbers to model the nested structure, but this approach fails due to the dynamic nature of the phone number keys.
Solution:
To handle nested dynamic structures, one should use a map instead of a fixed list to model the data. For this example, the following data structures can be used:
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"` }
In this updated structure, map[string]SMSPhone is used to represent the nested "sms" object, where the map keys correspond to the dynamic phone numbers.
To unmarshal the JSON data into these structures, the following code can be used:
var result SMSSendJSON if err := json.Unmarshal([]byte(src), &result); err != nil { panic(err) } fmt.Printf("%+v", result)
The result will be a Go struct with a map containing the nested dynamic phone number data.
Related questions showcasing the use of maps for dynamic structures in Go include:
The above is the detailed content of How to Parse JSON Data with Nested Dynamic Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!