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

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

Barbara Streisand
Release: 2024-11-26 10:06:10
Original
832 people have browsed it

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

Decoding Arrays with Mixed Types in JSON

When dealing with JSON arrays that contain values of different types, it's essential to consider how to unmarshal them into a Go program effectively. Go arrays require an explicitly defined type, which poses a challenge when handling varying value types.

Solution: Utilizing interface{}

The solution lies in using interface{}, a special type in Go that can hold values of any type. By using an interface{} array, we allow for the flexibility of storing values of different types within the same array.

Example Implementation

Consider the following JSON example:

{"key": ["NewYork", 123]}
Copy after login

To unmarshal this JSON using interface{}, we can define a custom data structure:

type UntypedJson map[string][]interface{}
Copy after login

This type represents a map from strings to arrays of interface{}, allowing for the possibility of storing values of any type.

Unmarshaling the JSON

To unmarshal the JSON, we can use the json.Unmarshal function:

var ut UntypedJson
json.Unmarshal([]byte(jsonString), &ut)
Copy after login

The ut variable will now contain the unmarshaled data as an UntypedJson type. The map keys correspond to the JSON object keys, and the array values hold the values of different types.

Example Playground

A complete example with an embedded Go playground can be found here:

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)
}
Copy after login

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