gpt4 book ai didi

javascript - 在 Javascript 中将 CSV 转换为嵌套的 JSON

转载 作者:行者123 更新时间:2023-11-29 17:50:35 25 4
gpt4 key购买 nike

我有一个 CSV 文件需要转换成 Javascript 对象/JSON 文件。这并不重要,因为无论如何我都会在 JS 中处理数据,而且两者都可以。

例如:

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

应该变成这样:

[
{
"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 来做的。

我希望尽可能在没有任何其他库的情况下在 vanilla JS 中完成此操作。

最佳答案

您可以通过递归创建对象来实现预期的结果。
看下面的代码:

var 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"
];

var attrs = csv.splice(0,1);

var result = csv.map(function(row) {
var obj = {};
var rowData = row.split(',');
attrs[0].split(',').forEach(function(val, idx) {
obj = constructObj(val, obj, rowData[idx]);
});
return obj;
})


function constructObj(str, parentObj, data) {
if(str.split('/').length === 1) {
parentObj[str] = data;
return parentObj;
}

var curKey = str.split('/')[0];
if(!parentObj[curKey])
parentObj[curKey] = {};
parentObj[curKey] = constructObj(str.split('/').slice(1).join('/'), parentObj[curKey], data);
return parentObj;
}

console.log(result);
.as-console-wrapper{max-height: 100% !important; top:0}

constructObj() 函数基本上通过查看列名递归地构造结果对象,所以如果列名包含 / 就像 house/address/street 它将通过名称 house 在对象中创建一个键,然后递归调用自身以获取字符串中剩余的其余键,即 address/street/。当字符串中不再有 / 时,递归结束,然后它简单地分配该键中的值并返回结果对象。

关于javascript - 在 Javascript 中将 CSV 转换为嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com