Dawko
Dawko

Reputation: 87

Javascript: How to convert an JSON arrays in array into an CSV file?

I'm struggeling with my JSON file here... This is what I get from my processing .php-file as a response:

{"1":{"Nachname":"Stromberg","Vorname":"Bernd", 
"Benutzername":"strombergbernd12","Password":"Xrz5Bv6A"},
"2":{"Nachname":"Heisterkamp","Vorname":"Ernie", 
"Benutzername":"heisterkampernie12","Password":"aOq24EpF"}}

Now, I want to build from this JSON array a csv file. In the first row the csv file should mention the headers Nachname, Vorname, Benutzername and Password and then list in the following rows the rest of the data.

I cant handle that, can you help me?

Upvotes: 3

Views: 13417

Answers (2)

You could use: Object.keys() and Object.values().

Something like this:

(function() {
  var data = {
    "1": {
      "Nachname": "Stromberg",
      "Vorname": "Bernd",
      "Benutzername": "strombergbernd12",
      "Password": "Xrz5Bv6A"
    },
    "2": {
      "Nachname": "Heisterkamp",
      "Vorname": "Ernie",
      "Benutzername": "heisterkampernie12",
      "Password": "aOq24EpF"
    }
  };
  var csv = Object.keys(data[Object.keys(data)[0]]).join(","); // Header columns.
  csv += "\n";
  for (var item in data) {
    csv += Object.values(data[item]).join(",");
    csv += "\n";
  }
  console.log(csv);
}());
.as-console-wrapper {
  position: relative;
  top: 0;
}

The result will be:

enter image description here

Upvotes: 0

Apolo
Apolo

Reputation: 4050

once you have your json as text you parse it:

var json = JSON.parse(jsonAsText);

transform it to an array:

json = Object.values(json);

init your result:

var csv = "";

keep header keys somewhere:

var keys = (json[0] && Object.keys(json[0])) || [];

write header row

csv += keys.join(',') + '\n';

iterate and put everything in csv

for (var line of json) {
  csv += keys.map(key => line[key]).join(',') + '\n';
}

Your csv content should be ready

var json = {
  "1": {
    "Nachname": "Stromberg",
    "Vorname": "Bernd",
    "Benutzername": "strombergbernd12",
    "Password": "Xrz5Bv6A"
  },
  "2": {
    "Nachname": "Heisterkamp",
    "Vorname": "Ernie",
    "Benutzername": "heisterkampernie12",
    "Password": "aOq24EpF"
  }
}

function toCSV(json) {
  json = Object.values(json);
  var csv = "";
  var keys = (json[0] && Object.keys(json[0])) || [];
  csv += keys.join(',') + '\n';
  for (var line of json) {
    csv += keys.map(key => line[key]).join(',') + '\n';
  }
  return csv;
}

console.log(toCSV(json));


Note: If you can, switch your json to Array syntax:

[
  {
    "Nachname":"Stromberg",
    "Vorname":"Bernd",
    "Benutzername":"strombergbernd12",
    "Password":"Xrz5Bv6A"
  },
  {
    "Nachname":"Heisterkamp",
    "Vorname":"Ernie", 
    "Benutzername":"heisterkampernie12",
    "Password":"aOq24EpF"
  }
]

and then remove this line:

json = Object.values(json);

Upvotes: 8

Related Questions