I need help flattening JSON in order to parse it as a CSV. The current flattening process is not working correctly, as the customer.addresses field is being filled with 'addresstype: r' and then skipping all other fields such as city, countrycode, countycode, etc. before moving on to customer.companyName. It seems like my JavaScript code needs some adjustment to properly flatten the nested JSON so that it can be displayed correctly in Excel. Any assistance with this issue would be greatly appreciated.
JSON (this is just a portion of the nested json and could vary in depth)
[
{
"countyCode": 12,
"customer": {
"addresses": [
{
"addressType": "R",
"city": "BRADENTON",
"countryCode": "US",
"countyCode": 12,
"foreignPostalCode": null,
"state": "FL",
"streetAddress": "819 15th Ave Dr E",
"zipCode": 34211,
"zipPlus": null
},
{
"addressType": "M",
"city": "BRADENTON",
"countryCode": "US",
"countyCode": 12,
"foreignPostalCode": null,
"state": "FL",
"streetAddress": "PO BOX 124",
"zipCode": 34201,
"zipPlus": 0124
}
],
--- Rest of the JSON data ---
JS
--- JavaScript functions for flattening objects ---
...functions here...
function flatten(object, addToList, prefix) {
Object.keys(object).map(key => {
if (object[key] === null) {
addToList[prefix + key] = "";
} else
if (object[key] instanceof Array) {
addToList[prefix + key] = listToFlatString(object[key]);
} else if (typeof object[key] == 'object' && !object[key].toLocaleDateString) {
flatten(object[key], addToList, prefix + key + '.');
} else {
addToList[prefix + key] = object[key];
}
});
return addToList;
}
Once I have defined these JavaScript functions, I run the JSON string through them using the following method:
// Run the JSON string through the flattening utilities above
var flatJSON = JSON.parse(evt.target.result).map(record => flatten(record, {}, ''));
var csv = Papa.unparse(flatJSON);