我将要把一个CSV文件转换成Javascript对象/JSON文件。不管是哪种格式转换,因为最终我会在JS中处理数据,所以都可以。
例如,这个CSV文件:
name,birthday/day,birthday/month,birthday/year,house/type,house/address/street,house/address/city,house/address/state,house/occupants
Lily Haywood,27,3,1995,Igloo,768 Pocket Walk,Honolulu,HI,7
Stan Marsh,19,10,1987,Treehouse,2001 Bonanza Street,South Park,CO,2
should become this:
[
{
"name": "Lily Haywood",
"birthday": {
"day": 27,
"month": 3,
"year": 1995
},
"house": {
"type": "Igloo",
"address": {
"street": "768 Pocket Walk",
"city": "Honolulu",
"state": "HI"
},
"occupants": 7
}
},
{
"name": "Stan Marsh",
"birthday": {
"day": 19,
"month": 10,
"year": 1987
},
"house": {
"type": "Treehouse",
"address": {
"street": "2001 Bonanza Street",
"city": "South Park",
"state": "CO"
},
"occupants": 2
}
}
]
这是我想到的:
function parse(csv){
function createEntry(header){
return function (record){
let keys = header.split(",");
let values = record.split(",");
if (values.length !== keys.length){
console.error("Invalid CSV file");
return;
}
for (let i=0; i<keys.length; i++){
let key = keys[i].split("/");
let value = values[i] || null;
/////
if (key.length === 1){
this[key] = value;
}
else {
let newKey = key.shift();
this[newKey] = this[newKey] || {};
//this[newKey][key[0]] = value;
if (key.length === 1){
this[newKey][key[0]] = value;
}
else {
let newKey2 = key.shift();
this[newKey][newKey2] = this[newKey][newKey2] || {};
this[newKey][newKey2][key[0]] = value;
//if (key.length === 1){}
//...
}
}
/////
}
};
}
let lines = csv.split("\n");
let Entry = createEntry(lines.shift());
let output = [];
for (let line of lines){
entry = new Entry(line);
output.push(entry);
}
return output;
}
我的代码能够工作,但是它有一个明显的缺陷:对于每个层级(例如
house/address/street
),我必须手动编写重复的if / else
语句。是否有更好的编写方式?我知道这涉及到某种递归或迭代,但我似乎无法弄清楚如何做。我在SO上搜索过,但大多数问题似乎是关于Python而不是JS的。尽可能地,我希望这可以在原生JS中完成,而不需要任何其他库。
attrs[0].split(',')
而不是attrs.split(',')
?attrs
不只是"name,birthday/day,..."
吗? - rapinopo.splice()
返回一个被删除元素的数组。因此attrs
将会是一个数组。 - abhishekkannojia