在 Javascript 中将 CSV 转换为嵌套 JSON

rap*_*opo 3 javascript csv json

我有一个 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
Run Code Online (Sandbox Code Playgroud)

应该变成这样:

[
    {
        "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
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

这就是我想出的:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的代码可以工作,但是它有一个明显的缺陷:对于它进入的每一层(例如house/address/street),我必须手动编写重复的if / else语句。

有没有更好的写法呢?我知道这涉及某种递归或迭代,但我似乎不知道如何实现。

我已经搜索过所以但大多数问题似乎都是用Python而不是JS来做的。

我希望尽可能在普通 JS 中完成此操作,而不需要任何其他库。

abh*_*jia 5

通过递归创建Object就可以达到预期的结果。
看下面的代码:

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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper{max-height: 100% !important; top:0}
Run Code Online (Sandbox Code Playgroud)

constructObj()函数基本上通过查看列名来递归地构造结果对象,因此如果列名中包含类似内容,/它将house/address/street按名称在对象中创建一个键house,然后递归地调用自身以获取字符串 ie 中的其余剩余键address/street//当字符串中不再剩下任何内容时,递归结束,然后它只是分配该键中的值并返回结果对象。