From the course: Go Standard Library
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Solution: Decoding JSON - Go Tutorial
From the course: Go Standard Library
Solution: Decoding JSON
- [Instructor] Now that you've tried the challenge, here's how I solved it. First, we initialize our products variable as an empty array of the product struct. This will be returned at the end of our function. So we initialize our variable by saying, "var products", which is an array of the product struct, and we will return products instead of nil. To deserialize the JSON string, we use the JSON unmarshal function. So we have our error variable just in case there's an error that occurs when we unmarshal. And we write JSON.unmarshal. We pass in our bite slice that we've casted to be when we pass in the JSON string, and then we also pass in a pointer to our products variable. We want to handle the error if it occurs. So, we will write an if statement that says, "if the error doesn't equal nil, we will return nil for the product and the error message." Now, when we run our code, you'll see that we get the list of products as an array of the product struct, and that's how you solve this…