프로젝트

일반

사용자정보

통계
| 개정판:

root / HServer / 00.Server / 00.Program / node_modules / safe-json-stringify / index.js

이력 | 보기 | 이력해설 | 다운로드 (1.2 KB)

1
var hasProp = Object.prototype.hasOwnProperty;
2

    
3
function throwsMessage(err) {
4
        return '[Throws: ' + (err ? err.message : '?') + ']';
5
}
6

    
7
function safeGetValueFromPropertyOnObject(obj, property) {
8
        if (hasProp.call(obj, property)) {
9
                try {
10
                        return obj[property];
11
                }
12
                catch (err) {
13
                        return throwsMessage(err);
14
                }
15
        }
16

    
17
        return obj[property];
18
}
19

    
20
function ensureProperties(obj) {
21
        var seen = [ ]; // store references to objects we have seen before
22

    
23
        function visit(obj) {
24
                if (obj === null || typeof obj !== 'object') {
25
                        return obj;
26
                }
27

    
28
                if (seen.indexOf(obj) !== -1) {
29
                        return '[Circular]';
30
                }
31
                seen.push(obj);
32

    
33
                if (typeof obj.toJSON === 'function') {
34
                        try {
35
                                return visit(obj.toJSON());
36
                        } catch(err) {
37
                                return throwsMessage(err);
38
                        }
39
                }
40

    
41
                if (Array.isArray(obj)) {
42
                        return obj.map(visit);
43
                }
44

    
45
                return Object.keys(obj).reduce(function(result, prop) {
46
                        // prevent faulty defined getter properties
47
                        result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
48
                        return result;
49
                }, {});
50
        };
51

    
52
        return visit(obj);
53
}
54

    
55
module.exports = function(data, replacer, space) {
56
        return JSON.stringify(ensureProperties(data), replacer, space);
57
}
58

    
59
module.exports.ensureProperties = ensureProperties;