Unmarshalling an Array of Diverse Types
In JSON handling, unmarshalling arrays with varied element types can be challenging. This article addresses the issue of unmarshalling arrays consisting of elements with known but unsorted data types.
Go's Method for Arbitrary Data Decoding
As outlined in Go's official documentation on JSON encoding, it is possible to decode arbitrary data into an interface{} using the json.Unmarshal function. By using type assertion, the data type can be dynamically determined.
Adapting Your Code
The following modified version of your code showcases this approach:
package main import ( "encoding/json" "fmt" ) var my_json string = `{ "an_array":[ "with_a string", { "and":"some_more", "different":["nested", "types"] } ] }` func IdentifyDataTypes(f interface{}) { switch vf := f.(type) { case map[string]interface{}: fmt.Println("is a map:") for k, v := range vf { switch vv := v.(type) { case string: fmt.Printf("%v: is string - %q\n", k, vv) case int: fmt.Printf("%v: is int - %q\n", k, vv) default: fmt.Printf("%v: ", k) IdentifyDataTypes(v) } } case []interface{}: fmt.Println("is an array:") for k, v := range vf { switch vv := v.(type) { case string: fmt.Printf("%v: is string - %q\n", k, vv) case int: fmt.Printf("%v: is int - %q\n", k, vv) default: fmt.Printf("%v: ", k) IdentifyDataTypes(v) } } } } func main() { fmt.Println("JSON:\n", my_json, "\n") var f interface{} err := json.Unmarshal([]byte(my_json), &f) if err != nil { fmt.Println(err) } else { fmt.Printf("JSON: ") IdentifyDataTypes(f) } }
Output
The code produces the following output:
JSON: { "an_array":[ "with_a string", { "and":"some_more", "different":["nested", "types"] } ] } JSON: is a map: an_array: is an array: 0: is string - "with_a string" 1: is a map: and: is string - "some_more" different: is an array: 0: is string - "nested" 1: is string - "types"
This approach allows for dynamic identification and handling of element types within the array, providing a versatile solution for your unmarshalling needs.
The above is the detailed content of How Can I Unmarshal a JSON Array with Mixed Data Types in Go?. For more information, please follow other related articles on the PHP Chinese website!