WhiteRabbit
WhiteRabbit

Reputation: 9

Json encoding with golang

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

Answers (1)

Amit Upadhyay
Amit Upadhyay

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:

  • Pre-process your raw string and bind your product in an array when it's not already an array. This way you will be able to Unmarshal it in a common way. But this will a workaround where you need to write unnecessarily write pre-processing code.
  • Just change the data from where you are getting it. Always save the product as an array, this will you can hit a GET call from your endpoint and it will always have a common format.

Upvotes: 2

Related Questions