Consuming slightly more complex JSON

I can’t seem to get anything back from json.Unmarshal when working with a complex JSON structure.

Here is an example of a response from Shopify’s API:

{“products”:[{“id”:2570195271760,“title”:“Sample Product”,“body_html”:“Example of an html body”}]}

I tried this:

    Resio, _ := ioutil.ReadAll(res.Body)

    JSONProducts := string(Resio)

    type Product struct {

        Id string `json:"id"`

    }

    type Response struct {

        Products []Product `json:"products"`

    }

    ProductsList := Response{}

    json.Unmarshal([]byte(JSONProducts), &ProductsList)

    fmt.Println(ProductsList.Products)

    fmt.Println(ProductsList)

But my responses look like this:

[{}]
{[{}]}

What am I doing wrong?

This code looks pretty much identical to the code I use to consume a rather complex json file, but I would try to add the title and body_html elements to the Product struct to see if that makes a difference (it shouldn’t though, I don’t consume all elements in my code either). Also print the string JSONProducts to make sure that string contains what you expect.

type Product struct {

        Id string `json:"id"`
        Title     `json:"title"`
        BodyHtml  `json:"body_html"
    }

Since the id property in your JSON input is a JSON number, you can’t unmarshal it as a Go string. Change the type of Id to int64 and add the two other properties:

type Product struct {
	Id    int64  `json:"id"`
	Title string `json:"title"`
	Body  string `json:"body_html"`
}

See https://play.golang.org/p/5T1XbpVYjo2 for a working example.

The output of this code is:

[{2570195271760 Sample Product Example of an html body}]
{[{2570195271760 Sample Product Example of an html body}]}

Thank you! Very clear solution.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.