Home  >  Article  >  Backend Development  >  How to Decode JSON with Dynamic Nested Keys in Go?

How to Decode JSON with Dynamic Nested Keys in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 12:01:15714browse

How to Decode JSON with Dynamic Nested Keys in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn