gpt4 book ai didi

使用 golang 进行 Json 编码

转载 作者:行者123 更新时间:2023-12-01 22:07:18 25 4
gpt4 key购买 nike

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"`

ShopifyProducts 结构。

Unmarshal 有什么问题?

最佳答案

正如我在您的 ShopifyProducts 中看到的那样struct您已声明 Products作为 array .但是在您的序列化字符串中 productobject .所以它无法解码该原始字符串。

您还说它在产品不止一个的情况下起作用。它在您的结构中的工作 coz Product 是一个数组。

可能的解决方案:

  • 预处理您的原始字符串并将您的产品绑定(bind)到一个数组中(当它还不是一个数组时)。这样,您将能够以一种常见的方式对其进行 Unmarshal。但这将是一种解决方法,您需要编写不必要的预处理代码。
  • 只需从您获取数据的位置更改数据。始终将产品保存为数组,这样您就可以从端点发起 GET 调用,并且它始终具有通用格式。
  • 关于使用 golang 进行 Json 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60683221/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com