Suppose I have have a JSON response body that looks something like this:
{
value: [{Object A's key-values}, {Object B's key-values}, {Object C's key-values} ...]
}
Where Object A, B, C are of different structures, although they may have same key names. (e.g. both Obj A and B could have the key "b", but only Obj A has the key "a")
I am only interested in Object A from the JSON response, the rest can be discarded. If I have a structure like this:
type MyObject struct{
a string
b string
}
type MyData struct{
value []MyObject
}
Will unmarshalling the response into MyData work? Can we specify a slice of a particular type such that only the desired element with the correct structure gets unmarhshalled and the rest of the objects in the JSON collection gets ignored?
CodePudding user response:
First: you need to export struct members:
type MyObject struct{
A string `json:"a"`
B string `json:"b"`
}
type MyData struct{
Value []MyObject `json:"value"`
}
Then, you can unmarshal the array using:
var v MyData
json.Unmarshal(input,&v)
This will create a MyObject
instance for every array element in the input, but only those that have a
and b
fields will be populated. Thus, you can filter the ones containing a
:
for _,x:=range v.Values {
if x.A!="" {
///
}
}