将 Uint8Array 解码为 JSON

Jac*_*opo 7 javascript python api reactjs uint8array

我正在从 API 获取数据以显示销售和财务报告,但我收到了一个 gzip 类型文件,我设法将其转换为 Uint8Array。我想以某种方式将其解析解码为 JSON 文件,我可以用它来访问数据并在前端创建图表。我尝试使用不同的库(pako 和 cborg 似乎是最接近用例的库),但最终出现错误Error: CBOR decode error: unexpected character at position 0

这是我到目前为止所拥有的代码:

let req = https.request(options, function (res) {
      console.log("Header: " + JSON.stringify(res.headers));
      res.setEncoding("utf8");
      res.on("data", function (body) {
        const deflatedBody = pako.deflate(body);
        console.log("DEFLATED DATA -----> ", typeof deflatedBody, deflatedBody);
        console.log(decode(deflatedBody));
      });
      res.on("error", function (error) {
        console.log("connection could not be made " + error.message);
      });
    });
    req.end();
  };
Run Code Online (Sandbox Code Playgroud)

我希望任何人都已经偶然发现了这一点并有一些想法。多谢!

ris*_*hav 12

请访问此答案/sf/answers/894379951/从响应中检索 GZIP 数据。

假设,您已经检索了 UInt8Array 形式的完整数据。

你只需要 UInt8Array 作为字符串

const jsonString = Buffer.from(dataAsU8Array).toString('utf8')

const parsedData = JSON.parse(jsonString)

console.log(parsedData)
Run Code Online (Sandbox Code Playgroud)

编辑

这对我有用

const {request} = require("https")
const zlib = require("zlib")


const parseGzip = (gzipBuffer) => new Promise((resolve, reject) =>{
    zlib.gunzip(gzipBuffer, (err, buffer) => {
        if (err) {
            reject(err)
            return
        }
        resolve(buffer)
    })
})

const fetchJson = (url) => new Promise((resolve, reject) => {
    const r = request(url)
    r.on("response", (response) => {
        if (response.statusCode !== 200) {
            reject(new Error(`${response.statusCode} ${response.statusMessage}`))
            return
        }

        const responseBufferChunks = []

        response.on("data", (data) => {
            console.log(data.length);
            responseBufferChunks.push(data)
        })
        response.on("end", async () => {
            const responseBuffer = Buffer.concat(responseBufferChunks)
            const unzippedBuffer = await parseGzip(responseBuffer)
            resolve(JSON.parse(unzippedBuffer.toString()))
        })
    })
    r.end()
})

fetchJson("https://wiki.mozilla.org/images/f/ff/Example.json.gz")
    .then((result) => {
        console.log(result)
    })
    .catch((e) => {
        console.log(e)
    })
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案对我不起作用。`Buffer.from(...)` 给出了 `Buffer` 未定义的错误。我猜Buffer是一个nodejs的东西,浏览器不支持。如果我只是在 Uint8Array 上运行“toString()”,它会生成一系列用逗号分隔的小数字。 (2认同)