我有一个JSON数据,但不幸的是我不知道如何将其解析为CSV。我刚开始学习并且对JSON完全没有任何线索,如果有人能够得到它的话,这将是很好的。
数据似乎如下:
{“姓名”:[“nowy”,“stary”],“学生姓名”:[[“ala”,“basia”,“”],[“basia”,“basia”],“学生索引“:[[1,2,0],[2,2]],”学生姓氏“:[[”alowa“,”basiowa“,”“],[”basiowa“,”basiowa“]]} < / p>
我试过这个解析器:
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
CSV += ReportTitle + '\r\n\n';
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var fileName = "Zestawienie_";
fileName += ReportTitle.replace(/ /g,"_");
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
但是输出在csv中看起来很丑陋(我有一行):
“的Nowy,斯达”, “ALA,BASIA ,, BASIA,BASIA”, “1,2,0,2,2”, “alowa,basiowa ,, basiowa,basiowa”
无论如何,这个函数适用于JSON:
{“车辆”:“宝马”,“日期”:“30,2013年7月09:24 AM”,“位置”:“Hauz Khas,Enclave,新德里,德里,印度”,“速度”:42 } {“车辆”:“奥迪”,“日期”:“30,2013年7月09:24 AM”,“位置”:“Hauz Khas,Enclave,新德里,德里,印度”,“速度”:42}。< / p>
似乎无法处理嵌套对象。
答案 0 :(得分:0)
以下是使用jq
的解决方案如果文件 keys_unsorted as $k
| $k, ([.[]] | transpose[])
| map(tostring)
| @csv
包含
data.json
和jq -M -r -f filter.jq data.json
包含您的示例数据,然后是命令
"names","Students names","Students indexes","Students surnames"
"nowy","[""ala"",""basia"",""""]","[1,2,0]","[""alowa"",""basiowa"",""""]"
"stary","[""basia"",""basia""]","[2,2]","[""basiowa"",""basiowa""]"
将产生
std::priority_queue