I'm trying to convert a JSON-object to a CSV file in javascript.
I have used all kinds of libraries and pre-made functions, but nothing seems to work for me as soon as the JSON starts to nest.
This is one of the functions I am using:
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;
}
I have seen people say that the complexity of your json object should not be of influence to to your output, but all I am getting is: [object Object],[object Object],[object Object], etc..
Online you can find json to csv converters that actually manage to create a nicely done csv file with extra headers if a property is double nested. So any hints in the right direction of how I would write a function like this would be really appreciated. If you know of any libraries that can do this that would be great too!
(It is probably worth stating that when I use a single-layered json object the csv file won't show [object,Object] and instead gives me a nice csv file, its only when it starts to get nested that it doesnt work anymore)
UPDATE: As requested, this is the kind of JSON file im working with.
[
{
"HEADER": {
"SEARCH": "Zoeken",
"FILTER": "Filter",
"MISC": "Overige"
},
"FORM": {
"REQUIRED": "Dit veld is verplicht",
"MINLENGTH": "De input is te kort",
"MAXLENGTH": "De input is te lang",
"EMAIL": "Geen geldig e-mailadres"
},
"TODO": "TODO: Hier moet nog een leuke tekst komen! dit komt uit een vertaling, in dit geval Nederlands. Nu is Nederlands natuurlijk op dit moment de enige taal maar het zou mooi zijn als hier in de toekomst veer vertalingen bij komen..."
}
]
I also wanted to add that when I use 'agnes.js' I don't get [Object object] as output, but instead every single letter is added underneath each other and there are no more than 1 column.
[object Object]toStringmethod always returns[object Object]for anobject. You can stringify it though.