将 CSV 转换为充满数字数组的 JSON 对象

Convert CSV to a JSON object full of number arrays

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

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

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

进入这个:

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

我试过的

尝试过像 this and this 这样的网站,但看不出如何根据我的需要调整它们。

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

对于发布的那种输入,手动将其转换为对象非常容易,方法是按换行符拆分并reduce转换为对象:

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);

您可以编写一个函数来执行您想要的操作,这并不难:

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 写入文件或在您的应用程序中进一步处理它。

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

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);