javascript - Nested JSON to CSV format Node.js -


i new programming , working on project received nested json response api using node.js. hoping find simple method convert json csv export. have searched around bit have tried jsonexport , nestedcsv2json packages, have not been able format quite right , unable iterate though json response.

basically json response follows:

{ '2016-01-31': { chats: 0, missed_chats: 5 }, '2016-02-01': { chats: 60, missed_chats: 7 }, '2016-02-02': { chats: 56, missed_chats: 1 }, '2016-02-03': { chats: 46, missed_chats: 0 }, '2016-02-04': { chats: 63, missed_chats: 2 }, '2016-02-05': { chats: 59, missed_chats: 4 }, '2016-02-06': { chats: 0, missed_chats: 1 } } 

the issue having size of can vary depending on date range user enters. need iterate through returned dates , extract nested json. 1 date or 100 dates.

i looking make csv format headers can export:

   date         chats    missed chats 2016-02-02        60            7 

this should quick , easy, struggling quite right. tips or appreciated. thanks!

this outputs semicolon separated csv-string. edit separator (for example replace tab \t) suit needs:

var json = { '2016-01-31': { chats: 0, missed_chats: 5 }, '2016-02-01': { chats: 60, missed_chats: 7 }, '2016-02-02': { chats: 56, missed_chats: 1 }, '2016-02-03': { chats: 46, missed_chats: 0 }, '2016-02-04': { chats: 63, missed_chats: 2 }, '2016-02-05': { chats: 59, missed_chats: 4 }, '2016-02-06': { chats: 0, missed_chats: 1 } };  var headers = 'date;chats;missed chats';  var csv = headers + '\r\n'; for(key in json){     csv += key + ';' + json[key].chats + ';' + json[key].missed_chats + '\r\n' } console.log(csv) 

the output is:

date;chats;missed chats 2016-01-31;0;5 2016-02-01;60;7 2016-02-02;56;1 2016-02-03;46;0 2016-02-04;63;2 2016-02-05;59;4 2016-02-06;0;1 

you can find working example here: https://jsfiddle.net/owd8zsa0/


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -