Reputation: 9
resp, err := http.Get(url + t.Keywords[0] + ".json")
if err != nil {
fmt.Println("error while getting productsRaw")
}
productsRaw, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("error while parsing body")
}
productsRawString := string(productsRaw)
productsData := ShopifyProducts{}
json.Unmarshal([]byte(productsRawString), &productsData)
fmt.Println(productsData.Products)\
this is my code for encoding json file from website and it works if it encoding more than one product
{"product":{"id":4420737073222,"title":"W AIR MAX VERONA","body_html":"\u003cp\u003e\u003cspan\u003eDesigned with every woman in mind, the mixed-material upper features a plush collar, flashy colours and unique stitching patterns. Nike Air cushioning combines with the lifted foam heel for a modern touch, adding comfort and style to your journey.\u003c\/span\u003e\u003c\/p\u003e\n\u003cp\u003e \u003c\/p\u003e\n\u003cp\u003e\u003cspan\u003e-Smooth
for example this what Println(productsRawString) show, so url works, but json.Unmarshal([]byte(productsRawString), &productsData) does't work.
type ShopifyProducts struct {
Products []struct {
BodyHTML string `json:"body_html"`
CreatedAt string `json:"created_at"`
Handle string `json:"handle"`
ID int `json:"id"`
Images []struct {
CreatedAt string `json:"created_at"`
Height int `json:"height"`
ID int `json:"id"`
Position int `json:"position"`
ProductID int `json:"product_id"`
Src string `json:"src"`
UpdatedAt string `json:"updated_at"`
VariantIds []interface{} `json:"variant_ids"`
Width int `json:"width"`
} `json:"images"`
ShopifyProducts structure.
Whats the problem with Unmarshal?
Upvotes: 0
Views: 636
Reputation: 7401
As I can see in your ShopifyProducts
struct
you have declared Products
as an array
. But in your serialized string product
is an object
. So it's not able to unmarshal that raw string.
You are also stating that it's working in case of product is more than one. Its working coz Product in your struct is an array.
Possible solutions:
Upvotes: 2