简体   繁体   English

将 Uint8Array 解码为 JSON

[英]Decode a Uint8Array into a JSON

I am fetching data from an API in order to show sales and finance reports, but I receive a type gzip file which I managed to convert into a Uint8Array.我正在从 API 获取数据以显示销售和财务报告,但我收到了一个类型的 gzip 文件,我设法将其转换为 Uint8Array。 I'd like to somehow parse-decode this into a JSON file that I can use to access data and create charts in my frontend with.我想以某种方式将其解析解码为一个 JSON 文件,我可以用它来访问数据并在我的前端创建图表。 I was trying with different libraries (pako and cborg seemed to be the ones with the closest use cases), but I ultimately get an error Error: CBOR decode error: unexpected character at position 0我正在尝试使用不同的库(pako 和 cborg 似乎是最接近用例的库),但我最终得到一个错误Error: CBOR decode error: unexpected character at position 0

This is the code as I have it so far:这是我到目前为止的代码:

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

I hope anyone has stumbled upon this already and has some idea.我希望有人已经偶然发现了这一点并有一些想法。 Thanks a lot!非常感谢!

Please visit this answer https://stackoverflow.com/a/12776856/16315663 to retrieve GZIP data from the response.请访问此答案https://stackoverflow.com/a/12776856/16315663以从响应中检索 GZIP 数据。

Assuming, You have already retrieved full data as UInt8Array.假设您已经检索到 UInt8Array 形式的完整数据。

You just need the UInt8Array as String你只需要 UInt8Array 作为字符串

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

const parsedData = JSON.parse(jsonString)

console.log(parsedData)

Edit编辑

Here is what worked for me这对我有用

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

Thank you, I actually just tried this approach and I get the following error:谢谢,我实际上只是尝试了这种方法,但出现以下错误:

SyntaxError: JSON Parse error: Unexpected identifier "x"语法错误:JSON 解析错误:意外的标识符“x”

But I managed to print the data in text format using the below function:但我设法使用以下函数以文本格式打印数据:

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

Now I would need to pass this into a JSON object.现在我需要将它传递给一个 JSON 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM