使用 Node.js 通过 C++ 将 CSV 转换为 JSON

将CSV转换为JSON

Aspose.Cells 支持将 CSV 转换为 JSON。为此,API 提供了 ExportRangeToJsonOptionsJsonUtility 类。ExportRangeToJsonOptions 类提供了导出范围到 JSON 的选项。ExportRangeToJsonOptions 类具有以下属性。

JsonUtility类使用与ExportRangeToJsonOptions类设置的导出选项导出JSON。

以下代码示例演示了使用 ExportRangeToJsonOptionsJsonUtility 类加载 源 CSV 文件 并在控制台打印 JSON 输出。

示例代码

const path = require("path");
const AsposeCells = require("aspose.cells.node");

// Source directory
const sourceDir = path.join(__dirname, "data");

const loadOptions = new AsposeCells.LoadOptions(AsposeCells.LoadFormat.Csv);
// Load CSV file
const filePath = path.join(sourceDir, "SampleCsv.csv");
const workbook = new AsposeCells.Workbook(filePath, loadOptions);
const lastCell = workbook.getWorksheets().get(0).getCells().getLastCell();

// Set JsonSaveOptions
const jsonSaveOptions = new AsposeCells.JsonSaveOptions();
const range = workbook.getWorksheets().get(0).getCells().createRange(0, 0, lastCell.getRow() + 1, lastCell.getColumn() + 1);
const data = AsposeCells.JsonUtility.exportRangeToJson(range, jsonSaveOptions);

// Print JSON
console.log(data);

控制台输出

[
{
"id": 1,
"language": "Java",
"edition": "third",
"author": "Herbert Schildt",
"streetAddress": 126,
"city": "San Jone",
"state": "CA",
"postalCode": 394221
},
{
"id": 2,
"language": "C++",
"edition": "second",
"author": "EAAAA",
"streetAddress": 126,
"city": "San Jone",
"state": "CA",
"postalCode": 394221
},
{
"id": 3,
"language": ".Net",
"edition": "second",
"author": "E.Balagurusamy",
"streetAddress": 126,
"city": "San Jone",
"state": "CA",
"postalCode": 394221
}
]