Home > Backend Development > Golang > How to Efficiently Unmarshal JSON with Dynamic Array Structures in Go?

How to Efficiently Unmarshal JSON with Dynamic Array Structures in Go?

Linda Hamilton
Release: 2024-12-21 14:43:11
Original
640 people have browsed it

How to Efficiently Unmarshal JSON with Dynamic Array Structures in Go?

Unmarshalling JSON with Dynamic Array Structure

When retrieving JSON data from third-party sources, the data structure can vary, sometimes containing arrays and sometimes not. This can pose challenges when using Go's json.Unmarshal function, as it expects a specific struct to match the JSON structure.

A common approach to handling this is to create a secondary struct with a slice, such as:

type ResponseWithSlice struct {
    Gwrcmds struct {
        Gwrcmd []struct { // Nested struct now a slice
            Gcmd  string
            Gdata struct {
                Gip struct {
                    Version string
                }
            }
        }
    }
}
Copy after login

This works, but it involves duplicating the struct, which can be cumbersome.

A more versatile solution involves using json.RawMessage:

type Response struct {
    RawGwrcmd json.RawMessage `json:"gwrcmds"`
}
Copy after login

With this approach, the gwrcmds field is stored as a raw JSON message, allowing us to peek into it and unmarshal it accordingly:

func (r *Response) UnmarshalJSON(b []byte) error {
    if err := json.Unmarshal(b, &r.RawGwrcmd); err != nil {
        return err
    }
    if r.RawGwrcmd[0] == '[' { // Check if it's an array
        return json.Unmarshal(r.RawGwrcmd, &r.Gwrcmds.Gwrcmd)
    }
    return json.Unmarshal(r.RawGwrcmd, &r.Gwrcmds.Gwrcmd) // Otherwise, treat it as a single struct
}
Copy after login

This method allows us to handle both array and non-array structures without the need for additional structs.

The above is the detailed content of How to Efficiently Unmarshal JSON with Dynamic Array Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template