Decoding JSON Arrays with Mixed Value Types
In some cases, you may encounter JSON arrays that contain elements of different types. For instance:
{["NewYork",123]}
Go arrays require you to explicitly specify their type, which can become challenging when dealing with arrays of mixed types.
Solution Using Interface{}
To handle mixed-type arrays, you can leverage the interface{} type, which allows values of any type. Here's how you can achieve this in Go:
package main import ( "encoding/json" "fmt" ) type UntypedJson map[string][]interface{} func main() { j := `{"NYC": ["NewYork",123]}` ut := UntypedJson{} err := json.Unmarshal([]byte(j), &ut) if err != nil { fmt.Println(err) return } fmt.Printf("%#v", ut) }
Note: It's worth noting that the provided JSON example is technically invalid, as JSON objects must have keys. A corrected example would be:
{"NYC": ["NewYork",123]}
The above is the detailed content of How to Decode JSON Arrays with Mixed Data Types in Go?. For more information, please follow other related articles on the PHP Chinese website!