Repository navigation
Expand file tree
/
Copy pathcsvToJSON.js
More file actions
66 lines (56 loc) · 1.89 KB
/
Copy pathcsvToJSON.js
File metadata and controls
66 lines (56 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//using AJAX + PHP for personal purpose
//you actually just need to get the file content by any mean, into the *responseText* variable
var lignes=[];
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/JS/AJAX/sendList.php'); //customize !
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
responseText=xhr.responseText;
// cuts file content into lines
// assuming the following:
// - the first one contains column titles
// - there are no non-wished 'CR', 'LF' or 'CR'+'LF' INSIDE a line
// choose the separator character below
// ###################################################################
// returns a JSON string (array of objects) from the initial content #
// ###################################################################
var i=0;
var j=0;
var ligne="";
var separator=',';
while(responseText.charAt(i)!="") {
if (/\r/g.test(responseText.charAt(i))) { // Mac EOL
i++;
if(/\n/g.test(responseText.charAt(i))) { // Windows EOL
i++;
ligne = responseText.substring(j,i-2);
}
else ligne = responseText.substring(j,i-1);
lignes.push(ligne.split(separator));
j=i;
}
else if ((/\n/g.test(responseText.charAt(i)))) { // Linux EOL
i++;
ligne = responseText.substring(j,i-1);
lignes.push(ligne.split(separator));
j=i;
}
else i++;
}
function Ligne (nomsChamps, valeursChamps) {
var l = nomsChamps.length;
for(var i=0;i<l;i++) {
this[nomsChamps[i]]=valeursChamps[i].trim();
}
return this;
}
nomsChamps=lignes.shift();
var l=lignes.length;
var tabLignes=[];
for (k=0;k<l;k++) {
tabLignes[k]=new Ligne(nomsChamps, lignes[k]);
}
console.log(JSON.stringify(tabLignes)); // you can get the formatted content here
}
});
xhr.send(null);