简体   繁体   English

在 javascript、typescript 中将 json 转换为 csv

[英]Converting json to csv in javascript, typescript

Hello I am trying to convert some json to cvs, but i have no luck parsing it, i have found some solution for simple json that looks like this您好我正在尝试将一些 json 转换为 cvs,但我没有运气解析它,我找到了一些简单的 json 的解决方案,看起来像这样

json =  [
    {
      name: "Anil Singh",
      age: 33,
      average: 98,
      approved: true,
      description: "I am active blogger and Author."
    },
    {
      name: 'Reena Singh',
      age: 28,
      average: 99,
      approved: true,
      description: "I am active HR."
    },
    {
      name: 'Aradhya',
      age: 4,
      average: 99,
      approved: true,
      description: "I am engle."
    },
  ];

And i have method like this我有这样的方法

convertToCSV(objArray, headerList): string {
    const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
    let str = '';
    let row = 'S.No,';
    // tslint:disable-next-line: forin
    for (const index in headerList) {
      row += headerList[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      // tslint:disable-next-line: forin
      for (const index in headerList) {
        const head = headerList[index];
        line += ',' + array[i][head];
      }
      str += line + '\r\n';
    }
    return str;
  }

And call it like this像这样称呼它

const csvData = this.convertToCSV(json, ['name', 'age', 'average', 'approved', 'description']);

The problem i have with one complex object that looks like this我有一个看起来像这样的复杂 object 的问题

json = [{
        "customer": {
            "emailAddress": "test@gmail.com"
        },
        "recommendationProductDetails": [{
            "productId": "4288",
            "title": "Title 1",
            "imageWebAddress": "http://url.com/GetImage/2956",
            "webAddress": "http://url.com/",
            "description": "Description 23"
        }, {
            "productId": "8888",
            "title": "Title 8",
            "imageWebAddress": "http://url.com/GetImage/2333",
            "webAddress": "http://url.com/",
            "description": "Description 55"
        }]
    },
    {
        "customer": {
            "emailAddress": "test33@gmail.com"
        },
        "recommendationProductDetails": [{
            "productId": "3333",
            "title": "Title 33",
            "imageWebAddress": "http://url.com/GetImage/333",
            "webAddress": "http://url.com/",
            "description": "Description 333"
        }, {
            "productId": "1111",
            "title": "Title 111",
            "imageWebAddress": "http://url.com/GetImage/111",
            "webAddress": "http://url.com/",
            "description": "Description 111"
        }]
    }
];

Can somebody help for formating this json in cvs, thanks有人可以帮助在 cvs 中格式化这个 json,谢谢

There slight workaround to convert such complex object into CSV将这种复杂的 object 转换为 CSV 有轻微的解决方法

Hope below code will be helpful希望下面的代码会有所帮助

var jsondata = [{
        "customer": {
            "emailAddress": "test@gmail.com"
        },
        "recommendationProductDetails": [{
            "productId": "4288",
            "title": "Title 1",
            "imageWebAddress": "http://url.com/GetImage/2956",
            "webAddress": "http://url.com/",
            "description": "Description 23"
        }, {
            "productId": "8888",
            "title": "Title 8",
            "imageWebAddress": "http://url.com/GetImage/2333",
            "webAddress": "http://url.com/",
            "description": "Description 55"
        }]
    },
    {
        "customer": {
            "emailAddress": "test33@gmail.com"
        },
        "recommendationProductDetails": [{
            "productId": "3333",
            "title": "Title 33",
            "imageWebAddress": "http://url.com/GetImage/333",
            "webAddress": "http://url.com/",
            "description": "Description 333"
        }, {
            "productId": "1111",
            "title": "Title 111",
            "imageWebAddress": "http://url.com/GetImage/111",
            "webAddress": "http://url.com/",
            "description": "Description 111"
        }]
    }
];



function flattenObjectKeys(ob) {
    var toReturn = {};

    for (var i in ob) {
        if (!ob.hasOwnProperty(i)) continue;

        if ((typeof ob[i]) == 'object' && ob[i] !== null) {
            var flatObject = flattenObjectKeys(ob[i]);
            for (var x in flatObject) {
                if (!flatObject.hasOwnProperty(x)) continue;

                toReturn[i + '.' + x] = flatObject[x];
            }
        } else {
            toReturn[i] = ob[i];
        }
    }
    return toReturn;
}

function transformToCSV(jsondata, keysArr=[])
{
    var csvData = "";
    var itemList = [];
    jsondata.forEach(customer=>{
        itemList.push(flattenObjectKeys(customer));
    })
    var newKeysNames = Object.keys(itemList[0]);
    var keysMap = {};
    newKeysNames.forEach(newKeyName => {
        keysArr.forEach((oldKeyName)=>{
            let findName = "."+ oldKeyName;
            if( String(newKeyName).indexOf(findName) >= 0)
            {

                keysMap[oldKeyName] = newKeyName;
            }
        })
    });
   // console.log("Keys Map === ", keysMap);
    itemList.forEach((item)=>{
        keysArr.forEach(keyName=>{
            csvData+=item[keysMap[keyName]] +",";
        })
        csvData+='\r\n';
    })


    return csvData;

}

console.log("====================");
console.log(transformToCSV(jsondata, ['title','webAddress','description']));
console.log("====================");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM