How to convert json data to csv where one key has nested value using javascript?

Viewed 25

I want to convert some json data to csv. But the problem is when a key has multiple value then it goes to seperate column after conversion. But I don't want to seperate inner value to different column. I have given the sample data below.

{
    "id": "axd4ffv-234rr-aaww-asa-jhu70099",
    "description": "{\"data\": \"abc Data\", \"data2\": [{\"name\": [\"xyzzzz\"]}",
   }

I want the description key value should show in same column. Like :

 id                               description                                                
 axd4ffv-234rr-aaww-asa-jhu70099  {"data": "abc Data", "data2": [{"name": ["xyzzzz"]}

But now the format is like :

 id                               description               another column                                 
 axd4ffv-234rr-aaww-asa-jhu70099  {"data": "abc Data"      "data2": [{"name": ["xyzzzz"]}

I tried the code below:

   function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
          var arrData = typeof JSONData != "object" ? JSON.parse(JSONData) : JSONData;
          var CSV = "";
          CSV += ReportTitle + "\r\n\n";
          if (ShowLabel) {
             var row = "";
            for (var index in arrData[0]) {
                //Now convert each value to string and comma-seprated
              row += index + ",";
            }
           row = row.slice(0, -1);

              //append Label row with line break
          CSV += row + "\r\n";
          }

           //1st loop is to extract each row
           for (var i = 0; i < arrData.length; i++) {
               var row = "";

//2nd loop will extract each column and convert it in string comma-seprated
           for (var index in arrData[i]) {
               row += '"' + arrData[i][index] + '",';
            }

           row.slice(0, row.length - 1);

         //add a line break after each row
         CSV += row + "\r\n";
      }

         if (CSV == "") {
           alert("Invalid data");
             return;
         }

      //Generate a file name
        var fileName = "file_";
    //this will remove the blank-spaces from the title and replace it with an underscore
       fileName += ReportTitle.replace(/ /g, "_");

       //Initialize file format you want csv or xls
       var uri = "data:text/csv;charset=utf-8," + CSV;
       var link = document.createElement("a");
       link.href = uri;
       link.style = "visibility:hidden";
       link.download = fileName + ".csv";
       document.body.appendChild(link);
     link.click();
    document.body.removeChild(link);
   }
0 Answers
Related