我有一个csv文件,其格式如下:
2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,
42540528726795050063891204319802818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0
2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,
42540529360620350178005905068154421248,42540529439848512692270242661698371583,SG,,,1.3667,103.8000,,0,0
我想只解析第一个逗号(IPv6地址)之后的项目,以及此记录的纬度/经度(第一个记录中的36.0000,138.0000)值。
如何使用JavaScript / jQuery执行此操作?
答案 0 :(得分:3)
使用split方法将字符串转换为数组,然后根据需要进行迭代。
var csv = "2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,4254052872679505006389120431980\n2818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0";
var myArray = csv.split("\n");//You should know what kind of new line your csv is using
myArray.map(function (e) { //Applies this function over each element of myArray that is each line of your csv
var line = e.split(","); //Turn the comma separated string into an array
return "The second element is: " + line[1]; //Do what you need
});
答案 1 :(得分:2)
就像你用任何语言一样。首先打开文件。逐行阅读。拆分逗号上的每一行。使用数组的索引来获取所需的值。
jQuery.get('file.csv', function(data) {
alert(data); // this is a line
var tempArray = data.split(','); // array of data
for(var i = 0; i < tempArray.length; i++)
{
console.log(tempArray[i]); // probably index 1 is your IPv6 address.
}
});
答案 2 :(得分:0)
答案 3 :(得分:0)
这是你做的:
$.ajax({
type: "GET",
url: "data.csv",
success: function (data) {
var data = Papa.parse(data);
var output = {
"IPv6" : data.data[0][1],
"coordinates" : [data.data[1][5], data.data[1][6]]
} /* -> These are the values you're looking for! */
}
});
因为我无法演示AJAX(由于跨域脚本问题),我将演示下面的success
函数!
var data = '2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,'+ "\n" +
'42540528726795050063891204319802818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0'+ "\n\n" +
'2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,'+ "\n" +
'42540529360620350178005905068154421248,42540529439848512692270242661698371583,SG,,,1.3667,103.8000,,0,0';
var success = function (data) {
var data = Papa.parse(data);
return output = {
"IPv6" : data.data[0][1],
"coordinates" : [data.data[1][5], data.data[1][6]]
}
}
document.body.innerHTML = '<pre>' + JSON.stringify(success(data), null, 2) + '</pre>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>