Miomir Dancevic
Miomir Dancevic

Reputation: 6852

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 =  [
    {
      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

json = [{
        "customer": {
            "emailAddress": "[email protected]"
        },
        "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": "[email protected]"
        },
        "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

Upvotes: 2

Views: 2133

Answers (1)

KishorRanga
KishorRanga

Reputation: 94

There slight workaround to convert such complex object into CSV

Hope below code will be helpful

var jsondata = [{
        "customer": {
            "emailAddress": "[email protected]"
        },
        "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": "[email protected]"
        },
        "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("====================");

Upvotes: 1

Related Questions