将原始 aws s3 xlsx 数据转换为 json

convert raw aws s3 xlsx data to json

我在 aws S3 中有一个 xlsx 文件,我想检索它并转换为 json。

我尝试了很多 xlsx 到 json 的转换器,但它们似乎都需要文件路径并且无法处理原始文件数据。 我能够转换为 wb 并获得 ws,但是 ws 数据包含大量无法传递给 json.

的 unicode
var AWS = require('aws-sdk');
var XLSX = require('xlsx');
util.s3_getObject(bucketName, fileName, true, false).then(data => {
    var wb = XLSX.read(data.data, {type:"buffer"});
    var ws;
    var target_sheet = "Sheet1";
    try {
        ws = wb.Sheets[target_sheet];
        console.log(JSON.parse(JSON.stringify(ws)));
        console.log(wb.SheetNames);
        if(!ws) {
            console.error("Sheet " + target_sheet + " cannot be found");
            process.exit(3);
        }
    } catch(e) {
        console.error("error parsing "+fileName+" "+target_sheet+": " + e);
    }
    console.log("converting sheet to json");

    data = XLSX.utils.sheet_to_json(JSON.parse(JSON.stringify(ws)));
    console.log("xlsx to json complete");
});

是否可以删除 unicode 或是否有更好的 xlsx 转换器可以帮助使用来自 s3.getObject 的原始数据?

error parsing input/xls/test.xlsx Sheet1: SyntaxError: Unexpected token u in JSON at position 0

我看到你已经设法得到了工作表。您可以使用 XLSX 库 (https://github.com/SheetJS/js-xlsx)。您可以尝试以下代码段。

var obj = XLSX.utils.sheet_to_row_object_array(worksheet);

这对我有用

var wb = XLSX.read(data.data, {type:"buffer"});
var ws;
var target_sheet = "Sheet1";
try {
    console.log("converting xlsx");
    ws = wb.Sheets[target_sheet];
    if(!ws) {
        console.error("Sheet " + target_sheet + " cannot be found");
        process.exit(3);
    }
} catch(e) {
    console.error("error parsing "+fileName+" "+target_sheet+": " + e);
    process.exit(4);
}
console.log("converting sheet to json");
data = JSON.stringify(XLSX.utils.sheet_to_json(ws));