Home > Backend Development > Golang > How to Unmarshal JSON with Variable Array Field Types in Go?

How to Unmarshal JSON with Variable Array Field Types in Go?

Barbara Streisand
Release: 2024-12-01 04:51:09
Original
514 people have browsed it

How to Unmarshal JSON with Variable Array Field Types in Go?

Unmarshalling JSON with a Variable Array Field Type in Go

In Go, JSON data is unmarshalled into a predefined struct. However, certain API responses can present challenges when the type of a key's value can vary between requests. For instance, an API might return either inline objects or object references for a specific key.

To handle this variability, consider using the following approach:

type Data struct {
    MyKey []interface{} `json:"mykey"`
}
Copy after login

This structure unmarshals both inline objects and object references into an array of interfaces. By using a type switch after unmarshalling, you can determine the actual type of each element in the array:

for _, v := range data.MyKey {
    switch x := v.(type) {
    case string:
        fmt.Println("Got a string: ", x)
    case map[string]interface{}:
        fmt.Printf("Got an object: %#v\n", x)
    }
}
Copy after login

This method allows you to parse JSON data with variable array field types in a flexible and idiomatic manner.

The above is the detailed content of How to Unmarshal JSON with Variable Array Field Types 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