如何从 csvtojson 范围中获取 JSON 数据?

How to get JSON data out of csvtojson scope?

我是 Javascript 的新手,也许你可以帮助我理解这一点。这里的 csvtojson 示例都显示了登录到控制台的工作正常:

https://www.npmjs.com/package/csvtojson#from-csv-file-to-json-array

const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
})

我的问题是 - 如何在此范围外 使用 jsonObj?我只想要一个简单的全局变量,我可以稍后在脚本中访问 JSON。

您可以使用“convert-excel-to-json”npm 包。举例如下:

'use strict';
const excelToJson = require('convert-excel-to-json');
 
const result = excelToJson({
    sourceFile: 'SOME-EXCEL-FILE.xlsx'
});
 
// result will be an Object containing keys with the same name as the sheets found on the excel file. Each of the keys will have an array of objects where each of them represents a row of the container sheet. e.g. for a excel file that has two sheets ('sheet1', 'sheet2')
{
    sheet1: [{
        A: 'data of cell A1',
        B: 'data of cell B1',
        C: 'data of cell C1'
    }],
    sheet2: [{
        A: 'data of cell A1',
        B: 'data of cell B1',
        C: 'data of cell C1'
    }]
}

然后您可以在任何地方使用结果对象。

你可以尝试使用asyncawait,写一些你想在IIFE中执行的代码,例如:

  const csvFilePath = './aCSV.csv';
  const csv = require('csvtojson');
    
  // a IIFE
  (async () => {
    const jsonObj = await csv().fromFile(csvFilePath);
    console.log(jsonObj);
    // [ { a: '1', b: '2', c: '3' }, { a: '4', b: '5', c: '6' } ]
  })();

您可以使用 IIFE(立即调用的函数表达式)来包装所有异步代码并将值存储在全局变量中,并且可以在异步 IIFE 中访问它。由于 js 的异步和单线程特性,要存储值并从任何地方访问它,您必须等待结果然后访问该值。

const csv = require('csvtojson');

let arr = [];

(async function () {
    const json = await csv().fromFile('./demo.csv');
    await arr.push(json);
    console.log(arr);
})()

我正在使用 convert-csv-to-json npm 包。 https://www.npmjs.com/package/convert-csv-to-json

let csv2Json = require('convert-csv-to-json');

let fileInputName = 'stores.csv';
let fileOutputName = 'stores.json';

csv2Json.fieldDelimiter(',').generateJsonFileFromCsv(fileInputName, fileOutputName);


let json = csv2Json.getJsonFromCsv("stores.csv");
for(let i=0; i<json.length;i++){
    console.log(json[i]);
}