我想做的是:

我想向此URL发送几个GET请求: https://catalog.wb.ru/brands/m/catalog?page=1&limit=300&brand=5786&dest=-1257786&sort=pricedown个 然后收集"产品"对象中的所有数据.键"Page"的值自动递增,以从所有页面获取数据.

实际上,我不太确定是否真的需要编写一个JSON来将其发送到前端.当我在for循环中得到新的响应时,发送不同的请求可能更好?

我做了什么:

做出了正确的 struct .对于单个请求,一切都运行得很好.

创建了requestBodyBytes []byteProductsBytes []byte,以便在它们后面加上ioutil.ReadAll中的[]bytes. 打印长度requestBodyBytes我看到它随着每个请求而扩展,但是在我解组它之后,我在输出中看到了空的 struct .

我理解这种情况的发生是因为每一个请求我都会得到type Response的新JSON.但是,如果我需要由来自几个JSON的type Response个"产品"对象组成的Product structs个切片怎么办?

注意:需要在for循环中初始化requestBodyBytes才能使用它停止发送请求,因为当页面上没有信息时,服务器会给出200个代码和空的JSON.

提前谢谢您!

const URL = "https://catalog.wb.ru/brands/m/catalog?page=%d&limit=300&brand=5786&dest=-1257786&sort=pricedown"

type Response struct {
    Data struct {
        Products []Product `json:"products"`
    } `json:"data"`
}

type Product struct {
    ID     int     `json:"id"`
    Name   string  `json:"name"`
    Price  int     `json:"priceU"`
    Rating float32 `json:"reviewRating"`
    Sale   int     `json:"sale"`
    New    bool    `json:"isNew"`
}

func main() {
    var response Response
    var products Response //Also tried to make it []Response
    var ProductsBytes []byte

    for i := 1; ; i++ {
        resp, err := http.Get(fmt.Sprintf(URL, i))
        if err != nil {
            fmt.Printf("#1 Error: %s", err)
        }
        defer resp.Body.Close()

        bytes, err := ioutil.ReadAll(resp.Body)
        var requestBodyBytes []byte
        requestBodyBytes = append(requestBodyBytes, bytes...)
        ProductsBytes = append(ProductsBytes, bytes...)

        json.Unmarshal(requestBodyBytes, &response)

        fmt.Println(resp.Status)
        fmt.Printf("\nSlice from page #%d\nLength of bytes: %d\n", i, len(bytes))
        fmt.Printf("Length of finalResult: %d\n", len(requestBodyBytes))
        if len(response.Data.Products) == 0 {
            fmt.Println("There's no more data")
            break
        }
    }

    json.Unmarshal(ProductsBytes, &products)

    fmt.Println(response)
    fmt.Println(products)
    fmt.Println(len(products))
}

推荐答案

没有理由收集所有原始响应字节.只需分别解组每个响应,并将每个页面的产品附加到包含所有产品的某个切片中.此外,在循环中呼叫defer resp.Body.Close()可能不是您想要的.延迟语句仅在循环结束后执行,因此连接不能重复用于请求.将循环体提取到它自己的函数中可以使这一点更加清晰:

package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "log"
    "net/http"
)

const URL = "https://catalog.wb.ru/brands/m/catalog?page=%d&limit=300&brand=5786&dest=-1257786&sort=pricedown"

type Response struct {
    Data struct {
        Products []Product `json:"products"`
    } `json:"data"`
}

type Product struct {
    ID     int     `json:"id"`
    Name   string  `json:"name"`
    Price  int     `json:"priceU"`
    Rating float32 `json:"reviewRating"`
    Sale   int     `json:"sale"`
    New    bool    `json:"isNew"`
}

func main() {
    var allProducts []Product

    for i := 1; ; i++ {
        page, err := fetchPage(i)
        if err != nil {
            log.Fatal(err) // TODO
        }

        allProducts = append(allProducts, page...)

        if len(page) == 0 {
            break
        }
    }

    fmt.Println(allProducts)
    fmt.Println(len(allProducts))
}

func fetchPage(i int) ([]Product, error) {
    resp, err := http.Get(fmt.Sprintf(URL, i))
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode != 200 {
        return nil, errors.New(resp.Status)
    }

    var response Response
    err = json.NewDecoder(resp.Body).Decode(&response)
    if err != nil {
        return nil, err
    }

    return response.Data.Products, nil
}

Json相关问答推荐

使用jolt删除空对象

Vega-Lite时钟(使用Vega-Lite中的计时器)

最新版本的Deneb在数据溢出时不支持滚动

如何用JQ更改空/布尔/数字的 colored颜色 ?

如何在我的响应模型中修复此问题:[期望的值类型为';Map<;Dynamic,Dynamic&>;,但获得的值类型为';NULL&39;]

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

XSLT 3.0 Json-to-xml,json 包含 html struct

使用 Groovy 将 XML 转换为 JSON

Powershell 7.2:ConvertFrom-Json - 日期处理

在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

Spring MVC 4:application/json内容类型设置不正确

PostgreSQL 中的 JSON 模式验证?

Jackson:忽略 Json 配置值

如何访问 JSON 对象数组的第一个元素?

字符串格式 JSON 字符串给出 KeyError

如何从 JSON 响应中提取单个值?

PHP json_encode json_decode UTF-8

JSON 和 BSON 哪个更轻量级?

将 JsonArray 添加到 JsonObject

从动态 json 数据更新力有向图上的链接