Reputation: 7986
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?
Upvotes: 1
Views: 80
Reputation: 3563
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'\n", err)
}
fmt.Printf("rec: %+v\n", 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.
Upvotes: 4