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]}
To unmarshal this JSON using interface{}, we can define a custom data structure:
type UntypedJson map[string][]interface{}
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)
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) }
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!