I need to integrate with an API that returns loads of elements in its response.
Is it possible to cherry-pick just the fields I want with go's json
library or do I need to deserialise the entire response?
I need to integrate with an API that returns loads of elements in its response.
Is it possible to cherry-pick just the fields I want with go's json
library or do I need to deserialise the entire response?
Yes.
Here's an example of having 2 fields in json and only decoding one:
jsonString := `{"a": 1, "b": 2}`
var rec struct {
A int `json:"a"`
}
err := json.Unmarshal([]byte(jsonString), &rec)
if err != nil {
log.Fatalf("json.Unmarshal() failed with '%s'
", err)
}
fmt.Printf("rec: %+v
", rec)
When run it prints:
rec: {A:1}
i.e. field "a" in json was decoded and field "b" was discarded.
See https://play.golang.org/p/89tu-ZC4pR for full example.