-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
76 lines (64 loc) · 1.59 KB
/
index.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
'use strict'
// ===================================================================
var parseCsv = require('csv-parser')
var pumpify = require('pumpify')
var through2 = require('through2')
var stripBomStream = require('strip-bom-stream')
// ===================================================================
var noop = Function.prototype
var hasOwn = Object.prototype.hasOwnProperty
function parseDynamic (data) {
var name, value
for (name in data) {
if (hasOwn.call(data, name)) {
value = data[name].toLowerCase()
if (value === 'true') {
data[name] = true
} else if (value === 'false') {
data[name] = false
} else if (value !== '') {
value = +value
if (!isNaN(value)) {
data[name] = value
}
}
}
}
}
function removeUndefinedProps (obj) {
Object.keys(obj).forEach(function (key) {
if (obj[key] === undefined) {
delete obj[key]
}
})
return obj
}
function csv2json (opts) {
opts || (opts = {})
var process = opts.dynamicTyping
? parseDynamic
: noop
return pumpify([
stripBomStream(),
parseCsv(removeUndefinedProps({
separator: opts.separator
})),
(function () {
var notFirst = false
var proxy = through2.obj(function (chunk, _, done) {
if (notFirst) {
this.push(',\n')
}
notFirst = true
process(chunk)
done(null, JSON.stringify(chunk))
}, function (done) {
this.push('\n]\n')
done()
})
proxy.push('[\n')
return proxy
})()
])
}
exports = module.exports = csv2json