将UINT8数组解码为JSON

2024-09-29 01:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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();
  };

我希望有人已经发现了这一点,并有了一些想法。 非常感谢


Tags: 文件logapijsononfunctionbodyres
2条回答

请访问此答案https://stackoverflow.com/a/12776856/16315663以从响应中检索GZIP数据

假设您已经以UInt8Array的形式检索到完整数据

您只需要将UInt8Array作为字符串

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

const parsedData = JSON.parse(jsonString)

console.log(parsedData)

编辑

这是对我有用的

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)
    })

谢谢,我实际上刚刚尝试过这种方法,但我得到了以下错误:

SyntaxError:JSON分析错误:意外标识符“x”

但我使用以下功能以文本格式打印数据:

getFinancialReports = (options, callback) => {
    // buffer to store the streamed decompression
    var buffer = [];

    https
      .get(options, function (res) {
        // pipe the response into the gunzip to decompress
        var gunzip = zlib.createGunzip();
        res.pipe(gunzip);

        gunzip
          .on("data", function (data) {
            // decompression chunk ready, add it to the buffer
            buffer.push(data.toString());
          })
          .on("end", function () {
            // response and decompression complete, join the buffer and return
            callback(null, buffer.join(""));
          })
          .on("error", function (e) {
            callback(e);
          });
      })
      .on("error", function (e) {
        callback(e);
      });
  };

现在我需要将其传递到JSON对象中

相关问题 更多 >