Home  >  Article  >  Backend Development  >  How to Parse JSON Data with Nested Dynamic Structures in Go?

How to Parse JSON Data with Nested Dynamic Structures in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 16:25:02195browse

How to Parse JSON Data with Nested Dynamic Structures in Go?

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:

  • How to parse/deserlize a dynamic JSON in Golang
  • How to unmarshal JSON with unknown fieldnames to struct in golang?
  • Unmarshal JSON with unknown fields
  • Unmarshal json string to a struct that have one element of the struct itself

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!

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