3

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?

10
  • 4
    What do you mean, "I can't handle that"? What have you tried? Commented Jan 18, 2018 at 15:54
  • well, I tried different codes of converting arrays and json's to csv files, but all I get is junk or nothing in the csv in the end. Commented Jan 18, 2018 at 15:54
  • You start from a JSON. CSV are Comma Separated Values. Therefore, you need to transform your data before exporting it to CSV. What's the expected output? Commented Jan 18, 2018 at 15:55
  • 2
    You need to include the different codes you've tried on your post. Commented Jan 18, 2018 at 15:55
  • 1
    Here is a hint, to get the headers for your csv, you can use Object.keys() Commented Jan 18, 2018 at 15:56

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

5 Comments

wow, you're a genius! I'm not used to json & javascript at all. Sorry for my dumb question - must have been pretty obvious to you. Thank you so much!
Note that json = Object.values(json); is a waste of ressource. If you can you should use the array syntax in your json (["item1", "item2", ...]) and remove this line
$header = array('Nachname', 'Vorname'); $results[$number] += array_combine($header, array($usernachname, $uservorname)); $results[$number] += array_combine($header, array($postuname, $pass)); How can I build your kind of Array? I dont get how to build it, and without the indexes, how can I call one specific item? Wait, actually I dont need to call one specific item...
Got it through a second array: $user = array(); $user += ['Nachname' => $usernachname]; $user += ['Vorname' => $uservorname]; $user += ['Benutzername' => $postuname]; $user += ['Password' => $pass]; $results[] = $user;
Had to replace your "for(var line of json)" to make it IE11 compatible. Danny's code helped me: for (var item in json) { csv += Object.values(json[item]).join(","); csv += "\n"; }
0

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

3 Comments

data[1] will fail with a single item ;)
@Apolo Fixed it. Thank you for the observation.
@DannyFardyJhonstonBermúdez took your for (var item in json) line to make it IE11 compatible - thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.