将Uint8Array解码为JSON



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

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

请访问此答案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对象中。