1

I want to generate a csv from array of Json data which I have below .

var keyDistribution =  [
                         [
                            {
                               "port": 4444,
                                "ipAddress": "52.35.15.121",
                                  "noOfKeys": 1
                                 },
                                 {
                                   "port": 2222,
                                   "ipAddress": "52.35.15.121",
                                   "noOfKeys": 1
                                 },
                                 {
                                   "port": 3333,
                                   "ipAddress": "52.35.15.121",
                                   "noOfKeys": 0
                                 }
                               ]
                             ];

How can I achieve this ?

I know how to generate a CSV from array as belows :

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
        var csvContent = "data:text/csv;charset=utf-8,";
        keyDistribution.forEach(function(infoArray, index){

           dataString = infoArray.join(",");
           csvContent += index < data.length ? dataString+ "\n" : dataString;

        }); 
        var encodedUri = encodeURI(csvContent);
        window.open(encodedUri);
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "my_data.csv");

        link.click();

But can some one please help me out how can I generate this data from Array of Json data (keyDistribution variable)?

I want the output in format :

[["port": 4444, "ipAddress": "52.35.15.121","noOfKeys": 1], ["port": 2222, "ipAddress": "52.35.15.121", "noOfKeys": 1]...];

EDIT I just want the heading in the columns as required. The CSV Snapshot

3
  • What you want is invalid - even though it is JavaScript or JSON. Commented Dec 2, 2015 at 11:57
  • Actually, there is no JSON. It is just an array (of arrays) of objects, instead of arrays. You can iterate through its keys using for and collect the same data. Commented Dec 2, 2015 at 11:57
  • 1
    Possible duplicate of Safely turning a JSON string into an object Commented Dec 2, 2015 at 12:30

1 Answer 1

1

All you need is to iterate over this array of arrays of objects, like this:

var csvContent = "data:text/csv;charset=utf-8,";

// Iterating through 0th index element as it contains all the objects
keyDistribution[0].forEach(function (infoArray, index) {

  // Fetching all keys of a single object
  var _keys = Object.keys(infoArray);
  var dataString = [];

  if(index==0){
     [].forEach.call(_keys, function(inst, i){
        dataString.push(inst);
     });
     dataString = dataString.join(",");
     csvContent += index < keyDistribution[0].length ? dataString + "\n" : dataString;
     dataString = [];
  }

  [].forEach.call(_keys, function(inst, i){
    dataString.push(infoArray[inst]);
  });

  // From here the code is same.
  dataString = dataString.join(",");
  csvContent += index < keyDistribution[0].length ? dataString + "\n" : dataString;

});
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");

link.click();
Sign up to request clarification or add additional context in comments.

7 Comments

Hi Void, I get an error for [].forEach.call(, function(inst, i){ saying Unexpected toke "," . Any idea what is the issue ?
Sorry my bad, check now.
That got resolved. But now I am getting "Uncaught TypeError: infoArray.join is not a function" error.
Thanks :) THat worked. Need a small favour. Can you also guide me like how can I set the header for the values that are being displayed in the CSV ? I have attached a screenGrab of my CSV in the edits section. I want Port, IP and the noOfKeys as the consecutive headings for the data. TIA :)
Done :) Thanks a lot once again :) And please do let me know about the header part.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.