不确定这一点-任何帮助,我们将不胜感激!
理想情况下,仅使用在线转换器,或者如果不使用节点程序包,我正在尝试转换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和this之类的网站,但看不到如何适应他们的需求。
非常感谢您对执行此操作的任何想法!
答案 0 :(得分:2)
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
答案 1 :(得分:1)
对于发布的输入类型,通过换行符分割并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);
答案 2 :(得分:1)
您可以编写一个可以实现所需功能的函数,这并不难:
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写入文件,或在您的应用程序中对其进行进一步处理。
答案 3 :(得分:0)
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);