I have been attempting to convert a JSON object to CSV using JavaScript, but the results are not as expected.
UPDATE: The JSON object is stored in a variable, and every time I try to access 'list', it returns as undefined. Is there a way to access the list through a variable?
Here is the JSON object I am working with:
{
"type": "success",
"message": "success",
"list": [
{
"ExtensionData": {},
"Address": "Baler",
"fld_test": "testMendoza",
"CocNumber": "1000000001",
"CustomerName": "test",
"IssueDate": "\\/Date(1584892800000)\\/",
"ProductName": "testProd",
"TransactionId": 1
},
{ ...additional JSON objects }
],
"totalPage": 0
}
I have tried using the following JavaScript function for the conversion, but the CSV file ends up empty:
function ConvertToCSV(objArray) {
alert("start json to csv conversion");
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;
}
The JSON code has been validated by online formatters, so I am curious if there is an issue with the JavaScript function?