我在这里使用我的JSON文件... 这是我从处理.php文件中获得的响应:
{"1":{"Nachname":"Stromberg","Vorname":"Bernd",
"Benutzername":"strombergbernd12","Password":"Xrz5Bv6A"},
"2":{"Nachname":"Heisterkamp","Vorname":"Ernie",
"Benutzername":"heisterkampernie12","Password":"aOq24EpF"}}
现在,我想从这个JSON数组构建一个csv文件。在第一行中,csv文件应提及标题Nachname,Vorname,Benutzername和Password,然后在以下行中列出其余数据。
我无法处理,你能帮助我吗?
答案 0 :(得分:3)
一旦你将json作为文本解析它:
var json = JSON.parse(jsonAsText);
将其转换为数组:
json = Object.values(json);
初始化你的结果:
var csv = "";
将标题密钥保留在某处:
var keys = (json[0] && Object.keys(json[0])) || [];
写标题行
csv += keys.join(',') + '\n';
迭代并将所有内容放入csv
for (var line of json) {
csv += keys.map(key => line[key]).join(',') + '\n';
}
您的csv内容应该准备就绪
var json = {
"1": {
"Nachname": "Stromberg",
"Vorname": "Bernd",
"Benutzername": "strombergbernd12",
"Password": "Xrz5Bv6A"
},
"2": {
"Nachname": "Heisterkamp",
"Vorname": "Ernie",
"Benutzername": "heisterkampernie12",
"Password": "aOq24EpF"
}
}
function toCSV(json) {
json = Object.values(json);
var csv = "";
var keys = (json[0] && Object.keys(json[0])) || [];
csv += keys.join(',') + '\n';
for (var line of json) {
csv += keys.map(key => line[key]).join(',') + '\n';
}
return csv;
}
console.log(toCSV(json));
注意:如果可以,请将json切换为Array语法:
[
{
"Nachname":"Stromberg",
"Vorname":"Bernd",
"Benutzername":"strombergbernd12",
"Password":"Xrz5Bv6A"
},
{
"Nachname":"Heisterkamp",
"Vorname":"Ernie",
"Benutzername":"heisterkampernie12",
"Password":"aOq24EpF"
}
]
然后删除此行:
json = Object.values(json);
答案 1 :(得分:0)
您可以使用:Object.keys()
和Object.values()
。
这样的事情:
(function() {
var data = {
"1": {
"Nachname": "Stromberg",
"Vorname": "Bernd",
"Benutzername": "strombergbernd12",
"Password": "Xrz5Bv6A"
},
"2": {
"Nachname": "Heisterkamp",
"Vorname": "Ernie",
"Benutzername": "heisterkampernie12",
"Password": "aOq24EpF"
}
};
var csv = Object.keys(data[Object.keys(data)[0]]).join(","); // Header columns.
csv += "\n";
for (var item in data) {
csv += Object.values(data[item]).join(",");
csv += "\n";
}
console.log(csv);
}());
.as-console-wrapper {
position: relative;
top: 0;
}
结果将是: