loc*_*boy 10 javascript asp.net api charts
有谁知道如何获取一个csv url文件并将其转换为json对象,以便我可以在js中使用谷歌图表工具?
aar*_*ell 18
我意识到这是一个老问题,但我今天遇到它需要做同样的事情并写了一个脚本来做到这一点.你可以在我的github repo上查看.
以下代码将完成您所使用的(使用jQuery):
$.ajax("http://my.domain.com/mycsvfile.csv", {
success: function(data) {
var jsonobject = csvjson.csv2json(data);
// Now use jsonobject to do some charting...
},
error: function() {
// Show some error message, couldn't get the CSV file
}
});
Run Code Online (Sandbox Code Playgroud)
快乐编码:)
帕斯帕斯(Papa Parse)对此很满意。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="libraries/PapaParse-4.1.2/papaparse.min.js"></script>
<script>
$(document).ready(function(){
$("#submitbutton").click(function(){
var myfile = $("#csvfile")[0].files[0];
var json = Papa.parse(myfile,
{
header: true,
skipEmptyLines: true,
complete: function(results) {
console.log("Dataframe:", JSON.stringify(results.data));
console.log("Column names:", results.meta.fields);
console.log("Errors:", results.errors);
}
});
})
})
</script>
</head>
<body>
<form name="foo" method="post" enctype="multipart/form-data">
<input id="csvfile" type="file" value="i">
</form>
<button id="submitbutton" type="button">Upload CSV file!</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
上传此 CSV:
+------+----------------+---------------+------------+
| Id | Petal.Length | Petal.Width | Species |
+======+================+===============+============+
| 1 | 1.4 | 0.2 | setosa |
+------+----------------+---------------+------------+
| 2 | 1.4 | 0.2 | setosa |
+------+----------------+---------------+------------+
| 3 | 1.3 | 0.2 | setosa |
+------+----------------+---------------+------------+
| 4 | 3.9 | 1.4 | versicolor |
+------+----------------+---------------+------------+
| 5 | 3.5 | 1 | versicolor |
+------+----------------+---------------+------------+
| 6 | 4.2 | 1.5 | versicolor |
+------+----------------+---------------+------------+
| 7 | 5.4 | 2.3 | virginica |
+------+----------------+---------------+------------+
| 8 | 5.1 | 1.8 | virginica |
+------+----------------+---------------+------------+
Run Code Online (Sandbox Code Playgroud)
你将在控制台中得到以下输出:
Dataframe: [{"Id":"1","Petal.Length":"1.4","Petal.Width":"0.2","Species":"setosa"},{"Id":"2","Petal.Length":"1.4","Petal.Width":"0.2","Species":"setosa"},{"Id":"3","Petal.Length":"1.3","Petal.Width":"0.2","Species":"setosa"},{"Id":"4","Petal.Length":"3.9","Petal.Width":"1.4","Species":"versicolor"},{"Id":"5","Petal.Length":"3.5","Petal.Width":"1","Species":"versicolor"},{"Id":"6","Petal.Length":"4.2","Petal.Width":"1.5","Species":"versicolor"},{"Id":"7","Petal.Length":"5.4","Petal.Width":"2.3","Species":"virginica"},{"Id":"8","Petal.Length":"5.1","Petal.Width":"1.8","Species":"virginica"}]
Column names: ["Id", "Petal.Length", "Petal.Width", "Species"]
Errors: []
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36593 次 |
最近记录: |