我正在尝试将示例csv文件加载到项目中,根据文件读取内容并显示。我完成了上传和文件写入,但未能正确优化json结构以备将来用例
以下是我的示例代码:
let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
var lines = [];
for(let i=0; i<json.length;i++){
console.log(json[i]);
lines.push(json[i])
}
console.log(lines);
var result3=JSON.stringify(lines);
result3 = result3.replace(/\r?\n|\r/g, " ");
console.log(result3);
我的输出:
console.log(json [i]) =
Object {name,age,address: "asd,20,"12/76, 11th cross"
"}
browser.js:5358 Object {name,age,address: "dff,30,"33, 11th cross"
"}
browser.js:5358 Object {name,age,address: "f,22,"7g/22, 12th cross"
"}
browser.js:5358 Object {name,age,address: "ghth,55,"4h, 13th cross"
"}
console.log(行) = [对象,对象,对象,对象,对象]
的console.log(result3)
[{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}]
我的预期输出:
{name:[],age:[],address:[]}
即我想要所有&#34; name&#34;值应存储在名称键中,类似于&#34; age&#34;和&#34;地址&#34;。有人可以帮我怎么做吗?
答案 0 :(得分:1)
从console.log(json[i])
输出显而易见,模块convert-csv-to-json
正在将您的csv文件转换为单个键值对的数组,这意味着name
,age
,{{ 1}}被连接成一个单元,同样适用于它们的价值。
此时您的文件密钥较少,您可以手动映射此密钥。
对于上述问题,您可以在逗号上使用address
和array#reduce
值。
split()
&#13;
答案 1 :(得分:0)
这应该有效
let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
let obj = JSON.parse(json);
let finalresult = obj.reduce((result, item) => {
Object.entries(item).forEach(([key, value]) => {
result[key] = result[key] || [];
result[key].push(value);
});
return result;
}, {});
答案 2 :(得分:0)
var jsonObj = [{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}];
var newArray = {
name:[],
age:[],
address:[]
};
for (var i in jsonObj) {
let [name, age, ...address] = jsonObj[i]["name,age,address"].split(',');
newArray.name.push(name);
newArray.age.push(age);
newArray.address.push(address.join(''));
};
console.log(newArray);
&#13;