[英]Decode a Uint8Array into a 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)
})
謝謝,我實際上只是嘗試了這種方法,但出現以下錯誤:
語法錯誤: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 對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.