Home > Backend Development > Golang > How to Unmarshal JSON Data with Variable Types: String or Array of Strings?

How to Unmarshal JSON Data with Variable Types: String or Array of Strings?

Linda Hamilton
Release: 2024-10-29 02:58:02
Original
501 people have browsed it

How to Unmarshal JSON Data with Variable Types: String or Array of Strings?

Decoding JSON with Variant Structures

The endpoint you're consuming returns JSON in varying formats, sometimes as a string and other times as an array. To handle this inconsistency, the following question explores the best approach to designing a Go struct that can accommodate both types.

The Question:

How can I create a Go struct that can unmarshal JSON data with variable types, either a string or an array of strings? Is there an elegant solution beyond attempting to decode into two separate structs?

The Answer:

A more sophisticated approach involves unmarshaling the JSON into an interface{} type. This type-agnostic approach allows for dynamic handling of different value types.

To implement this technique, create a struct with a field of type interface{}, as demonstrated in the following example:

<code class="go">type Response struct {
    Message interface{} `json:"message"`
}</code>
Copy after login

When unmarshaling the JSON data into this struct, you can use a type switch or type assertion to determine the actual type of the Message field. This allows you to process the data accordingly.

Here's an example implementation:

<code class="go">func main() {
    inputs := []string{
        `{"message":"Message"}`,
        `{"message":["ERROR_CODE"]}`,
    }

    for _, input := range inputs {
        var r Response
        if err := json.Unmarshal([]byte(input), &r); err != nil {
            panic(err)
        }
        switch x := r.Message.(type) {
        case string:
            fmt.Println("Success, message:", x)
        case []interface{}:
            fmt.Println("Error, code:", x)
        default:
            fmt.Println("Something else:", x)
        }
    }
}</code>
Copy after login

Output:

Success, message: Message
Error, code: [ERROR_CODE]
Copy after login

By utilizing the interface{} approach, you gain flexibility in handling JSON data with varying types, simplifying your codebase.

The above is the detailed content of How to Unmarshal JSON Data with Variable Types: String or Array of Strings?. 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