-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsvutil.js
82 lines (82 loc) · 1.32 KB
/
csvutil.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
exports.convertCSVtoArray = function(s) {
const res = []
let st = 0
let line = []
let sb = null
if (!s.endsWith("\n"))
s += "\n"
const len = s.length
for (let i = 0; i < len; i++) {
let c = s.charAt(i)
if (c == '\r')
continue
if (st == 0) {
if (c == '\n') {
if (line.length > 0)
line.push("")
res.push(line)
line = []
} else if (c == ',') {
line.push("")
} else if (c == '"') {
sb = ""
st = 2
} else {
sb = c
st = 1
}
} else if (st == 1) {
if (c == '\n') {
line.push(sb)
res.push(line)
line = []
st = 0
sb = null
} else if (c == ',') {
line.push(sb)
sb = null
st = 0
} else {
sb += c
}
} else if (st == 2) {
if (c == '"') {
st = 3
} else {
sb += c
}
} else if (st == 3) {
if (c == '"') {
sb += c
st = 2
} else if (c == ',') {
line.push(sb)
sb = null
st = 0
} else if (c == '\n') {
line.push(sb)
res.push(line)
line = []
st = 0
sb = null
}
}
}
if (sb != null)
line.push(sb)
if (line.length > 0)
res.push(line)
return res
}
exports.csv2json = function(csv) {
const res = []
const head = csv[0]
for (let i = 1; i < csv.length; i++) {
const d = {}
for (let j = 0; j < head.length; j++) {
d[head[j]] = csv[i][j]
}
res.push(d)
}
return res
}