将JSON嵌套为CSV格式的Node.js [英] Nested JSON to CSV format Node.js
问题描述
我是编程新手,正在从事一个项目,该项目使用node.js从API接收到嵌套的JSON响应.我希望找到一种简单的方法来将此JSON转换为CSV以进行导出.我已经搜索了一些尝试过jsonexport和nestedcsv2json包的信息,但是我无法获得正确的格式,并且无法通过JSON响应进行迭代.
I am new to programming and am working on a project that received a nested JSON response from an API using node.js. I am hoping to find a simple method to convert this JSON into a CSV for export. I have searched around a bit have tried jsonexport and nestedcsv2json packages, but I have not been able to get my format quite right and am unable to iterate though my JSON response.
基本上,JSON响应如下:
Basically the JSON response is as 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 } }
我遇到的问题是,它的大小可能会根据用户输入的日期范围而有所不同.因此,我将需要遍历返回的日期,然后提取嵌套的JSON.可以是一个日期或100个日期.
The issue I am having is that the size of this can vary depending on the date range that the user enters. So I will need to iterate through the returned dates and then extract the nested JSON. It could be one date or 100 dates.
我希望使用可以导出的标头制作CSV格式:
I am looking to make a CSV format with headers that I can export:
Date Chats Missed Chats
2016-02-02 60 7
这应该是简单快捷的,但是我很难做到这一点.任何提示或帮助,我们将不胜感激.谢谢!
This should be quick and easy, but I am struggling to get this quite right. Any tips or help is greatly appreciated. Thanks!
推荐答案
这将输出以分号分隔的csv字符串.编辑分隔符(例如,用选项卡\t
替换它)以适合您的需求:
This outputs a semicolon separated csv-string. Edit the separator (for example replace it with tab \t
) to suit your 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)
输出为:
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
您可以在此处找到一个有效的示例: https://jsfiddle.net/owd8zsa0/
You can find a working example here: https://jsfiddle.net/owd8zsa0/
这篇关于将JSON嵌套为CSV格式的Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!