-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathjsont.js
80 lines (67 loc) · 1.61 KB
/
jsont.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
'use strict';
const jpath = require('./jpath');
function replaceAll(s, from, to) {
return s.split(from).join(to);
}
function transform(obj,rules) {
var objName = '$';
var isArray = false;
for (var n in obj) {
objName = n;
break;
}
var arrRules = [];
for (var r in rules) {
var rule = {};
rule.rule = rules[r];
rule.ruleName = r;
rule.processed = false;
arrRules.push(rule);
}
for (var r=arrRules.length-1;r>=0;r--) {
var inner = arrRules[r].rule;
if (arrRules[r].ruleName.indexOf('[*]') > 0) {
isArray = true;
}
for (var o in obj) {
var newObjName = objName;
if (isArray) {
newObjName = o;
}
var elements;
if (typeof inner === 'function') {
if (o == arrRules[r].ruleName) {
elements = [inner(obj[arrRules[r].ruleName])];
}
else {
elements = [];
}
}
else {
elements = inner.split(/[\{\}]+/);
}
for (var i=1;i<elements.length;i=i+2) {
elements[i] = replaceAll(elements[i], '$',arrRules[r].ruleName);
elements[i] = replaceAll(elements[i], '[*]','['+o+']'); //specify the current index
elements[i] = replaceAll(elements[i], 'self','');
elements[i] = jpath.fetchFromObject(obj,elements[i]);
if (elements[i] == null) {
elements = []; //abort
}
if (Array.isArray(elements[i])) {
elements[i] = elements[i].join(''); // avoid commas being output
}
}
if (elements.length>0) {
obj[newObjName] = elements.join('');
}
if (!isArray) continue;
}
arrRules[r].processed = true;
}
if (Array.isArray(obj)) return obj[0]
else return obj[objName];
}
module.exports = {
transform : transform
};