-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (51 loc) · 1.87 KB
/
index.js
File metadata and controls
53 lines (51 loc) · 1.87 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
const JSONPath = require('jsonpath').JSONPath;
const pathExpressionRegexp = /(\$(\.{1,2}(\*|\w{1,})){0,}(\[[\w.<>*@&:?\s\-,"=()]{1,}\]){0,})/g;
class UtJSONPath extends JSONPath {
transform(source, template, obj = {}, key) {
if (Array.isArray(template)) {
const path = template[0];
const subpath = template[1];
const arr = this.query(source, path)[0];
if (arr.length && subpath) {
obj = obj[key] = [];
arr.forEach((record, i) => {
this.transform(record, subpath, obj, i);
});
} else {
obj[key] = arr;
}
} else if (typeof template === 'object') {
if (typeof key !== 'undefined') {
obj = obj[key] = {};
}
for (let prop in template) {
this.transform(source, template[prop], obj, prop);
}
} else if (typeof template === 'string') {
const matches = template.match(pathExpressionRegexp);
let value;
if (matches) {
if (matches.length === 1) {
value = this.query(source, matches[0])[0];
} else {
value = matches.reduce((template, match) => {
return template.replace(match, (replacement) => {
return this.query(source, match)[0] || replacement;
});
}, template);
}
} else {
value = template;
}
if (key) {
obj[key] = value;
} else {
obj = value;
}
}
return obj;
}
}
const instance = new UtJSONPath();
instance.JSONPath = UtJSONPath;
module.exports = instance;