Home >Backend Development >Golang >How Can I Unmarshal JSON Arrays with Mixed Data Types in Go?

How Can I Unmarshal JSON Arrays with Mixed Data Types in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-27 07:06:10327browse

How Can I Unmarshal JSON Arrays with Mixed Data Types in Go?

Unmarshaling JSON Arrays with Mixed Value Types

Unmarshalling a JSON array containing values of varying types can pose a challenge in Go due to the requirement for explicit type definition in Go arrays.

Case Study:

Consider the following invalid JSON example:

["NewYork", 123]

An attempt to decode this array into a Go array would fail because the Go array requires a fixed type, which is unknown in this case.

Solution:

To overcome this limitation, Go provides the interface{} type, which allows for the storage of values of any type. By utilizing interface{}, it becomes possible to unmarshal JSON arrays containing mixed value types, as demonstrated below:

const j = `{"NYC": ["NewYork", 123]}`

type UntypedJson map[string][]interface{}

func main() {
    ut := UntypedJson{}
    fmt.Println(json.Unmarshal([]byte(j), &ut))
    fmt.Printf("%#v", ut)
}

In this example, we define a custom type UntypedJson as a map of string keys to slices of interface{}. The JSON array is then unmarshaled into the UntypedJson instance. The fmt.Printf statement displays the unmarshaled data, which contains the mixed values from the JSON array.

By utilizing the interface{} type, it becomes possible to unmarshal JSON arrays containing values of varying types, providing a more flexible and versatile solution for complex data scenarios.

The above is the detailed content of How Can I Unmarshal JSON Arrays with Mixed Data Types 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