Answer the question
In order to leave comments, you need to log in
What is the difference between json.Unmarshal and json.NewDecoder?
What is the fundamental difference between the two methods when parsing json? In what cases is it best to use them?
resp, err := http.Get(requestURL)
if err != nil {
// ...
}
defer resp.Body.Close()
req := &respData{}
if err := json.NewDecoder(resp.Body).Decode(req); err != nil {
// ...
}
resp, err := http.Get(requestURL)
if err != nil {
// ...
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// ...
}
var restResponse RestResponse
if err := json.Unmarshal(body, &restResponse); err != nil {
// ...
}
Answer the question
In order to leave comments, you need to log in
json.Unmarshal uses an array of bytes, while json.NewDecoder is a streaming parser that doesn't need to keep all the data in memory for parsing at once.
For parsing json from a file or from a request, I would advise json.NewDecoder, as it will consume less memory (no need to read an array of bytes into memory in advance).
json.NewDecoder is used when interacting with the API, and json.Unmarshal when working with data from memory - for example, we took an array of data from the database and then process it
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question