0

I need to export json data to csv file. I used this code as reference and modified as per my requirement.But I'm not able to export nested data successfully.

JSON:(Structure of my JSON)

{
"id":"101",
"name":"User1",
"place":{ 
    "city":"City1",
    "state":"State1"
    },
"access":[{"status":"available"}],
"date" : ["2014-03-06"]
}

Below is my javascript function.

function convertToCSV(objArray) {
  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  var str = '';

  for (var i = 0; i < array.length; i++) {
    var line = '';
    for (var index in array[i]) {
      if (line != '') line += ','

      line += array[i][index];
    }

    str += line + '\r\n';
  }

  return str;
}

function exportCSVFile(headers, items, fileTitle) {
  if (headers) {
    items.unshift(headers);
  }

  // Convert Object to JSON
  var jsonObject = JSON.stringify(items);

  var csv = this.convertToCSV(jsonObject);

  var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

  var blob = new Blob([csv], {
    type: 'text/csv;charset=utf-8;'
  });
  if (navigator.msSaveBlob) { // IE 10+
    navigator.msSaveBlob(blob, exportedFilenmae);
  } else {
    var link = document.createElement("a");
    if (link.download !== undefined) { // feature detection
      // Browsers that support HTML5 download attribute
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", exportedFilenmae);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      console.log(link.href)
      link.click();
      document.body.removeChild(link);
    }
  }
}

var headers = {
  id: "ID".replace(/,/g, ''), // remove commas to avoid errors
  name: "Name",
  place: "Place",
  city: "City",
  state: "State",
  access: "Access",
  date: "Date"
};

itemsNotFormatted = [{
    "id": "101",
    "name": "User1",
    "place": {
      "city": "City1",
      "state": "State1"
    },
    "access": [{
      "status": "available"
    }],
    "date": ["2014-03-06"]
  },
  {
    "id": "102",
    "name": "User2",
    "place": {
      "city": "City2",
      "state": "State2"
    },
    "access": [{
      "status": "unavailable"
    }],
    "date": ["2016-04-06"]
  }
];

var itemsFormatted = [];

// format the data
itemsNotFormatted.forEach((item) => {
  itemsFormatted.push({
    id: item.id.replace(/,/g, ''), // remove commas to avoid errors,
    name: item.name,
    place: item.place,
    city: item.place.city,
    state: item.place.state,
    access: item.access.status,
    date: item.date
  });
});

var fileTitle = 'orders'; // or 'my-unique-title'

exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download

Output: With the above json data,I need to get the output as: ExpectedOutput

Please help me to achieve this.

mplungjan
  • 134,906
  • 25
  • 152
  • 209
Thra
  • 67
  • 5
  • I'd recommend looking into some existing packages: https://www.npmjs.com/package/json2csv or https://www.npmjs.com/package/json-2-csv – wp78de Jan 21 '21 at 18:12
  • If you prioritize having working code on in a timely manner, you could create a json object that matches EXACTLY with your excel columns and use Javascript to convert your nested object to that excel-export object. This way you have made exporting to excel trivial. I do not consider this "code duplication" as the model of your application is different then the model of Excel, so making this difference explicit and applying a transformation between the two models seems plausible. – user1884155 Jan 21 '21 at 18:22

0 Answers0