-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathto-edn.js
44 lines (41 loc) · 978 Bytes
/
to-edn.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
let jsedn = require('jsedn')
let atoms = require('jsedn/lib/atoms')
function guessKeyword(xs) {
return xs.every(x => {
return x.match(/^[a-z][a-z-]*[\?\!]?$/)
})
}
exports.toEdn = function toEdn(jsonObj) {
if (typeof jsonObj === 'string') {
return jsonObj
}
if (typeof jsonObj === 'number') {
return new jsedn.BigInt(jsonObj)
}
if (typeof jsonObj === 'bigint') {
return new jsedn.BigInt(jsonObj)
}
if (typeof jsonObj === 'boolean') {
return jsonObj
}
if (jsonObj == null) {
return null
}
if (Array.isArray(jsonObj)) {
let xs = jsonObj.map(toEdn)
return new jsedn.Vector(xs)
}
if (typeof jsonObj === 'object') {
let betterUseKeyword = guessKeyword(Object.keys(jsonObj))
let ret = []
for (let k in jsonObj) {
if (betterUseKeyword) {
ret.push(new jsedn.Keyword(':' + k))
} else {
ret.push(k)
}
ret.push(toEdn(jsonObj[k]))
}
return new jsedn.Map(ret)
}
}