UNPKG

1.96 kBJavaScriptView Raw
1/**
2 * ToloJSON can parse JSON with comments, and can stringify JSON with indentation and comments.
3 * This is useful for configuration files.
4 */
5
6function stringify(js, indent, indentUnit) {
7 if (typeof indent === 'undefined') indent = '';
8 if (typeof indentUnit === 'undefined') indentUnit = ' ';
9 var t = typeof js;
10 if (t === 'string') {
11 return JSON.stringify(js);
12 }
13 if (t === 'number') {
14 return js;
15 }
16 if (t === 'boolean') {
17 return js ? "true" : "false";
18 }
19 var out = '', txt, small, lastIndent;
20 if (Array.isArray(js)) {
21 out = '[';
22 txt = JSON.stringify(js);
23 small = txt.length < 40;
24 if (!small) out += "\n" + indent;
25 js.forEach(
26 function(itm, idx) {
27 if (idx > 0) {
28 out += "," + (small ? " " : "\n" + indent);
29 }
30 out += stringify(itm, indent + indentUnit);
31 }
32 );
33 out += ']';
34 return out;
35 }
36 if (t === 'object') {
37 lastIndent = indent;
38 indent += indentUnit;
39 out = '{';
40 txt = JSON.stringify(js);
41 small = txt.length < 40;
42 if (!small) out += "\n" + indent;
43 var k, v, idx = 0;
44 for (k in js) {
45 v = js[k];
46 if (idx > 0) {
47 out += "," + (small ? " " : "\n" + indent);
48 }
49 out += JSON.stringify(k) + ": " + stringify(v, indent);
50 idx++;
51 }
52 out += (small ? "" : "\n" + lastIndent) + '}';
53 return out;
54 }
55 return '"<' + t + '>"';
56}
57
58
59exports.parse = function(json) {
60 return JSON.parse(json);
61};
62
63exports.stringify = function(js, indent) {
64 if (typeof indent === 'undefined') indent = false;
65 if (indent === false) {
66 return JSON.stringify(js);
67 }
68 return stringify(js, '', indent);
69};