Home > Article > Backend Development > How to Handle Varying JSON Value Types When Unmarshaling in Go?
Unmarshaling JSON with Varying Value Types in Go
In Go, JSON unmarshaling typically involves mapping JSON data to a corresponding struct. However, difficulties arise when the data structure can vary, presenting the value of a key as an array of objects or strings.
Problem:
An API delivers inconsistent data structures, resulting in potential value variations for a key: inline objects or references to objects (/obj1/is/at/this/path).
Solution:
To handle this variability, consider the following techniques:
1. Unmarshal to an Interface Type:
Un marshal the JSON data to a struct containing a field with type []interface{}. This will allow both strings (decoded as strings) and objects (decoded as map[string]interface{}) to be stored in the array.
Code Sample:
type Data struct { MyKey []interface{} `json:"mykey"` }
2. Type Switching for Differentiation:
Once the data is unmarshaled, use a type switch to distinguish between strings and objects.
Code Sample:
for i, v := range data.MyKey { switch x := v.(type) { case string: fmt.Println("Got a string: ", x) case map[string]interface{}: fmt.Printf("Got an object: %#v\n", x) } }
Additional Notes:
The above is the detailed content of How to Handle Varying JSON Value Types When Unmarshaling in Go?. For more information, please follow other related articles on the PHP Chinese website!