[英]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)\
這是我從網站編碼 json 文件的代碼,如果它編碼多個產品,它就可以工作
{"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
例如 Println(productsRawString) 顯示的內容,因此 url 有效,但 json.Unmarshal([]byte(productsRawString), &productsData) 不起作用。
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"`
Shopify 產品結構。
Unmarshal 有什么問題?
正如我在您的ShopifyProducts
struct
看到的,您ShopifyProducts
Products
聲明為array
。 但是在你的序列化字符串product
是一個object
。 所以它無法解組那個原始字符串。
您還說明它在產品不止一種的情況下有效。 它在結構中的工作因為 Product 是一個數組。
可能的解決方案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.