Go to unmarshal json with a field which is an array of objects or strings
Come in, you decouple the json into a structure. The problem is that I have an api that can change the type of the key value from the request to the request.
For example, objects that can be embedded objects such as:
{
"mykey": [
{obj1},
{obj2}
]
}
but also point to objects by keys, for example:
{
"mykey": [
"/obj1/is/at/this/path",
"/obj2/is/at/this/other/path"
]
}
Some objects can be embedded, but others link to multiple locations.
In javascript or python this won't be a problem. Just check the type.
What is the idealistic way to untie and disassemble these two objects? Does the only way reflect?
source to share
You can decouple this JSON with a structure similar to the following:
type Data struct {
MyKey []interface{} `json:"mykey"`
}
If the JSON contains strings, they will be decoded as strings in the array. If the JSON includes objects, they will be decoded as map[string]interface{}
. You can distinguish between them using the switch. Something like that:
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)
}
}
You can play with this example here: http://play.golang.org/p/PzwFI2FSav
source to share