我的 csv 文件如下:
NAME,AGE
"John","23"
"BOB","24"
执行下面的代码时,我得到{}
的是警报而不是 JSON 对象。我的预期输出应该是以下格式的 JSON 文件:
{
"items": [
{
"NAME": "John",
"AGE": " 23"
},
{
"NAME": "BOB",
"AGE": "24"
},
]
}
代码:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
var lines = {};
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.csv",
dataType: "csv",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
alert(lines);
}
var val = JSON.stringify(lines);
alert(val);
</script>
</head>
<body>
</body>
</html>