liaoxujun@qq.com
2024-02-18 b73ffe97fc885b652b20328c1c3d079a9124fb89
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
; (function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory)
    } else if (typeof exports === 'object') {
        module.exports = factory()
    } else {
        root.JSONfns = factory()
    }
})(this, function () {
    const ARROWFN_PREFIX = '__ARFn__'
    const REGEXP_PREFIX = '__RGXP__'
 
    const replacer = (key, value) => {
        const fnBody = value !== null && value !== undefined ? value.toString() : ''
 
        if (value instanceof Function || typeof value === 'function') {
            if (fnBody.indexOf('function') !== 0) {
                return ARROWFN_PREFIX + fnBody
            }
 
            return fnBody
        }
 
        if (value instanceof RegExp) {
            return REGEXP_PREFIX + fnBody
        }
 
        return value
    }
 
    const reviver = (key, value) => {
        if (typeof value !== 'string') {
            return value
        }
        else if (value.indexOf('function') === 0) {
            /* eslint-disable-next-line no-eval */
            return eval(`(${value})`)
        }
        else {
            return value
        }
 
        if (
            value.indexOf(ARROWFN_PREFIX) === 0 ||
            value.indexOf(REGEXP_PREFIX) === 0
        ) {
            /* eslint-disable-next-line no-eval */
            return eval(value.slice(8))
        }
    }
 
    return {
        stringify: (obj, space) => JSON.stringify(obj, replacer, space),
        parse: str => JSON.parse(str, reviver)
    }
})