我试过了:
$("#dvCSV").append(JSON.stringify(dataArray, null, '\t'));
但输出是:
关于SO的{p> This answer是完美的,但是我尝试应用它但没有管理它,这是可以玩的jsFiddle:[{" 20":" 10"," Barcellona":" Cagliari"," Dipendenti": " Dipendenti" },{" 20":" 15"," Barcellona":" Sassari"," Dipendenti":&# 34; Dipendenti" },{" 20":" 22"," Barcellona":"都灵"," Dipendenti":&# 34; Dipendenti" } ]
$(function () {
var csv = $("#fileUpload").val();
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var rows = e.target.result.split("\r\n");
if(rows.length>0){
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
$("#dvCSV").append(JSON.stringify(dataArray, null, '\t'));
}
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
function GetCSVCells(row, separator){
return row.split(separator);
}
&#13;
#heading { font-size: x-large; font-weight: bold; }
.text { width: 99%; height: 200px; }
.small { font-size: small; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="file" id="fileUpload" name="fileUpload" />
<input type="button" id="upload" value="Upload" name="upload"/>
<hr />
<div id="dvCSV"></div>
&#13;
答案 0 :(得分:3)
由于您将此附加到HTML元素,因此需要类似于将它设置为white-space
到pre-wrap
,以便正确包装。
Stack snippet
var arr = [ { "20": "10", "Barcellona": "Cagliari", "Dipendenti": "Dipendenti" }, { "20": "15", "Barcellona": "Sassari", "Dipendenti": "Dipendenti" }, { "20": "22", "Barcellona": "Torino", "Dipendenti": "Dipendenti" } ];
document.getElementById('dvCSV').innerHTML = JSON.stringify(arr, null, '\t');
#dvCSV {
white-space: pre-wrap
}
<div id="dvCSV"></div>
答案 1 :(得分:1)
它工作正常with spaces,如:
JSON.stringify(arr, null, ' '); // Using 2 spaces as the 'space' argument
var arr = [ { "20": "10", "Barcellona": "Cagliari", "Dipendenti": "Dipendenti" }, { "20": "15", "Barcellona": "Sassari", "Dipendenti": "Dipendenti" }, { "20": "22", "Barcellona": "Torino", "Dipendenti": "Dipendenti" } ];
console.log(JSON.stringify(arr, null, ' '));
&#13;