]>
Commit | Line | Data |
---|---|---|
1 | var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); | |
2 | ||
3 | module.exports = function (obj, opts) { | |
4 | if (!opts) opts = {}; | |
5 | if (typeof opts === 'function') opts = { cmp: opts }; | |
6 | var space = opts.space || ''; | |
7 | if (typeof space === 'number') space = Array(space+1).join(' '); | |
8 | var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; | |
9 | ||
10 | var cmp = opts.cmp && (function (f) { | |
11 | return function (node) { | |
12 | return function (a, b) { | |
13 | var aobj = { key: a, value: node[a] }; | |
14 | var bobj = { key: b, value: node[b] }; | |
15 | return f(aobj, bobj); | |
16 | }; | |
17 | }; | |
18 | })(opts.cmp); | |
19 | ||
20 | var seen = []; | |
21 | return (function stringify (node, level) { | |
22 | var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; | |
23 | var colonSeparator = space ? ': ' : ':'; | |
24 | ||
25 | if (node && node.toJSON && typeof node.toJSON === 'function') { | |
26 | node = node.toJSON(); | |
27 | } | |
28 | if (typeof node !== 'object' || node === null) { | |
29 | return json.stringify(node); | |
30 | } | |
31 | if (isArray(node)) { | |
32 | var out = []; | |
33 | for (var i = 0; i < node.length; i++) { | |
34 | var item = stringify(node[i], level+1); | |
35 | out.push(indent + space + item); | |
36 | } | |
37 | return '[' + out.join(',') + indent + ']'; | |
38 | } | |
39 | else { | |
40 | if (seen.indexOf(node) !== -1) { | |
41 | if (cycles) return stringify('__cycle__'); | |
42 | throw new TypeError('Converting circular structure to JSON'); | |
43 | } | |
44 | else seen.push(node); | |
45 | ||
46 | var keys = objectKeys(node).sort(cmp && cmp(node)); | |
47 | var out = []; | |
48 | for (var i = 0; i < keys.length; i++) { | |
49 | var key = keys[i]; | |
50 | var keyValue = stringify(key,0) | |
51 | + colonSeparator | |
52 | + stringify(node[key],level+1) | |
53 | ; | |
54 | out.push(indent + space + keyValue); | |
55 | } | |
56 | return '{' + out.join(',') + indent + '}'; | |
57 | } | |
58 | })(obj, 0); | |
59 | }; | |
60 | ||
61 | var isArray = Array.isArray || function (x) { | |
62 | return {}.toString.call(x) === '[object Array]'; | |
63 | }; | |
64 | ||
65 | var objectKeys = Object.keys || function (obj) { | |
66 | var has = Object.prototype.hasOwnProperty || function () { return true }; | |
67 | var keys = []; | |
68 | for (var key in obj) { | |
69 | if (has.call(obj, key)) keys.push(key); | |
70 | } | |
71 | return keys; | |
72 | }; |