retrocycle.js
1.46 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
import reviver from './reviver';
import muteProperty from './util/muteProperty';
import { CYCLIC_KEY } from '../constants';
// eslint-disable-next-line no-control-regex
const pathReg = /^\$(?:\[(?:\d+|"(?:[^\\"\u0000-\u001f]|\\([\\"/bfnrt]|u[0-9a-zA-Z]{4}))*")])*$/;
export default function retrocycle(json) {
const $ = JSON.parse(json, reviver);
if (typeof $ !== 'object' || $ === null) {
return $;
}
(function rez(value) {
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i += 1) {
const item = value[i];
if (item && typeof item === 'object') {
const path = item.$ref;
if (typeof path === 'string' && pathReg.test(path)) {
value[i] = eval(path); // eslint-disable-line no-eval, no-param-reassign
} else {
rez(item);
}
}
}
} else {
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for (const name in value) {
const item = value[name];
if (typeof item === 'object' && item !== null) {
const path = item.$ref;
if (typeof path === 'string' && pathReg.test(path)) {
value[name] = eval(path); // eslint-disable-line no-eval, no-param-reassign
} else {
rez(item);
}
}
}
}
}
})($);
muteProperty(CYCLIC_KEY, $);
return $;
}