I want to convert JSON responses to CSV format. Since the JSON response may differ, I can't manually create my headers.
I looked around and found a programmatic solution on stack overflow. But this solution uses the keys of the JSON as headers. My test data is sensitive so I'll post a similar JSON response that gives a better idea of what I'm trying to do.
{
"response":[{
"_id": "5cfe7d3c6deeeef08ce0444b",
"name": "Debra Milligain",
"phone": "+1 (906) 432-2182",
"address": "676 Merit Court, Steinhatchee, Oregon, 5491",
"tags": [
"consequat",
"reprehenderit",
"amet"
],
"Work": {
"skills": [{
"id": 0,
"name": "Programming"
},
{
"id": 1,
"name": "Business"
}
]
},
"friends": [{
"id": 0,
"name": "Stafford Hernandez"
},
{
"id": 1,
"name": "Colleen Christensen"
},
{
"id": 2,
"name": "Barker Keith"
}
],
"greeting": [],
"favoriteFruit": "banana"
}]}
Solution found from hereChristian Landgren 's Solution
function json2csv(json) {
const items = json.response;
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
//console.log(csv)
}
This is the actual response:
_id,name,phone,address,tags,Work,friends,greeting,favoriteFruit
"5cfe7d3c6deeeef08ce0444b","Debra Milligain","+1 (906) 432-2182","676 Merit Court, Steinhatchee, Oregon, 5491",["consequat","reprehenderit","amet"],{"skills":[{"id":0,"name":"Programming"},{"id":1,"name":"Business"}]},[{"id":0,"name":"Stafford Hernandez"},{"id":1,"name":"Colleen Christensen"},{"id":2,"name":"Barker Keith"}],[],"banana"
The output as the headers but doesn't include the sub headers. The actual output should be this more or less.
"_id","name","phone","address","tags","Work__skills__id","Work__skills__name","friends__id","friends__name","favoriteFruit"
"5cfe7d3c6deeeef08ce0444b","Debra Milligain","+1 (906) 432-2182","676 Merit Court, Steinhatchee, Oregon, 5491","consequat","0","Programming","0","Stafford Hernandez","banana"
"","","","","reprehenderit","1","Business","1","Colleen Christensen",""
"","","","","amet","","","2","Barker Keith",""