【问题标题】:Convert CSV to a JSON object full of number arrays将 CSV 转换为一个包含数字数组的 JSON 对象
【发布时间】:2019-05-20 10:56:46
【问题描述】:

不确定这一点 - 非常感谢任何帮助!

理想情况下,仅使用在线转换器,或者如果不是节点包,我正在尝试像这样转换 CSV 文件:

Cat,31.2,31.2
Dog,35,1
Tree,32.4

进入这个:

"myObj":{
   "Cat":[
      31.2,
      31.2
   ],
   "Dog":[
      35,
      1
   ],
   "Tree":[
      32.4
   ]
}

我尝试过的

尝试过thisthis 等网站,但不知道如何根据自己的需要调整它们。

非常感谢您提供有关如何执行此操作的任何想法!

【问题讨论】:

  • 很确定myObj 中的最后一个键应该是Tree,而不是Cat,对吧?
  • 是的,你是对的,很棒的地方@CertainPerformance!

标签: node.js json csv npm converters


【解决方案1】:
const fs = require('fs');
const csv = fs.readFileSync(process.argv[2], 'utf8');
const obj = csv.split(/\r?\n/g)
  .filter(line => line.trim())
  .map(line => line.split(','))
  .reduce(
    (o, [key, ...values]) => Object.assign(o, { [key]: values.map(Number) }),
    {}
  );

fs.writeFileSync(process.argv[3], JSON.stringify(obj, null, 3), 'utf8');

将其保存到csv2json.js 或类似名称后,您可以在命令行上使用它,如下所示:

node csv2json input.csv output.json

【讨论】:

  • 非常感谢所有回复!选择这个是正确的,因为它是最完整的 - 尽管如果有人需要类似的东西 - 为了我的需要,我必须将空单元格从 0 更改为空,将值转换为数字并删除空行。
【解决方案2】:

对于发布的输入类型,手动将其转换为对象非常容易,通过换行符和reduceing 拆分为对象:

const input = `Cat,31.2,31.2
Dog,35,1
Tree,32.4`;
const obj = input.split('\n').reduce((a, line) => {
  const [, heading, rest] = line.match(/^([^,]+),(.*)/);
  a[heading] = rest.split(',');
  return a;
}, {});
console.log(obj);

【讨论】:

    【解决方案3】:

    你可以写一个函数来做你想做的事,这并不难:

    function csv2json (csv) {
      let arr = csv.split('\n'), // Split your CSV into an array of lines
          obj = {}               // Your object to later fill data into
    
      for (let i = 0; i < arr.length; i++) {
        let line = arr[i].split(',')    // Split the line into an array
    
        obj[line.shift()] = line        // Remove the first item from the array 
                                        // and use it as the key in the object,
                                        // assigning the rest of the array to
                                        // that key
      }
    
      return obj   // Return your object
    }
    

    您可以稍后使用 fs.writeFile(...) 将 JSON 写入文件,或在您的应用程序中进一步处理它。

    【讨论】:

      【解决方案4】:

      const str = `Cat,31.2,31.2
      Dog,35,1
      Tree,32.4`;
      
      const obj = str.split('\n').reduce((accu, curr) => {
          curr = curr.split(',');
          let first = curr.shift();
          accu[first] = [...curr];
          return accu;
      }, {});
      
      console.log(obj);

      【讨论】:

        猜你喜欢
        • 2016-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多