-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfastjson_ref_resolver.src.js
62 lines (56 loc) · 1.39 KB
/
fastjson_ref_resolver.src.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
'use strict';
function isObject(v) {
return null != v && typeof v == 'object';
}
function RefResolver(o) {
if (!isObject(o)) {
throw "Only object or array can be resolved";
}
this.root = o;
}
RefResolver.prototype.resolve = function() {
var root = this.root;
function safeEval(expression) {
var v = root;
var refs = expression.split(/[\.\[\]]+/);
for (var i = 0, j = refs.length; i < j; ++i) {
var ref = refs[i];
if (!ref) continue;
if (isNaN(ref)) {
v = v[ref];
} else {
v = v[parseInt(ref)];
}
}
return v;
}
function process(o, context, key) {
// console.log(o);
// console.log(context);
// console.log(key);
// console.log("---");
for (var p in o) {
if (o.hasOwnProperty(p)) {
var v = o[p];
if (isObject(v)) {
process(v, o, p);
} else {
if ('$ref' == p) {
v = (v.substring(1));
var v2 = safeEval(v);
context[key] = v2;
}
}
}
}
}
try {
process(root);
} catch (e) {
console.error(e);
}
return root;
}
module.exports = {
Resolver: RefResolver
};