prettyjson.js
7.21 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
'use strict';
// ### Module dependencies
var colors = require('colors/safe');
var Utils = require('./utils');
exports.version = require('../package.json').version;
// Helper function to detect if an object can be directly serializable
var isSerializable = function(input, onlyPrimitives, options) {
if (
typeof input === 'boolean' ||
typeof input === 'number' ||
typeof input === 'function' ||
input === null ||
input instanceof Date
) {
return true;
}
if (typeof input === 'string' && input.indexOf('\n') === -1) {
return true;
}
if (options.inlineArrays && !onlyPrimitives) {
if (Array.isArray(input) && isSerializable(input[0], true, options)) {
return true;
}
}
return false;
};
var addColorToData = function(input, options) {
if (options.noColor) {
return input;
}
if (typeof input === 'string') {
// Print strings in regular terminal color
return options.stringColor ? colors[options.stringColor](input) : input;
}
var sInput = input + '';
if (input === true) {
return colors.green(sInput);
}
if (input === false) {
return colors.red(sInput);
}
if (input === null) {
return colors.grey(sInput);
}
if (typeof input === 'number') {
return colors[options.numberColor](sInput);
}
if (typeof input === 'function') {
return 'function() {}';
}
if (Array.isArray(input)) {
return input.join(', ');
}
return sInput;
};
var indentLines = function(string, spaces){
var lines = string.split('\n');
lines = lines.map(function(line){
return Utils.indent(spaces) + line;
});
return lines.join('\n');
};
var renderToArray = function(data, options, indentation) {
if (isSerializable(data, false, options)) {
return [Utils.indent(indentation) + addColorToData(data, options)];
}
// Unserializable string means it's multiline
if (typeof data === 'string') {
return [
Utils.indent(indentation) + '"""',
indentLines(data, indentation + options.defaultIndentation),
Utils.indent(indentation) + '"""'
];
}
if (Array.isArray(data)) {
// If the array is empty, render the `emptyArrayMsg`
if (data.length === 0) {
return [Utils.indent(indentation) + options.emptyArrayMsg];
}
var outputArray = [];
data.forEach(function(element) {
// Prepend the dash at the begining of each array's element line
var line = '- ';
if (!options.noColor) {
line = colors[options.dashColor](line);
}
line = Utils.indent(indentation) + line;
// If the element of the array is a string, bool, number, or null
// render it in the same line
if (isSerializable(element, false, options)) {
line += renderToArray(element, options, 0)[0];
outputArray.push(line);
// If the element is an array or object, render it in next line
} else {
outputArray.push(line);
outputArray.push.apply(
outputArray,
renderToArray(
element, options, indentation + options.defaultIndentation
)
);
}
});
return outputArray;
}
if (data instanceof Error) {
return renderToArray(
{
message: data.message,
stack: data.stack.split('\n')
},
options,
indentation
);
}
// If values alignment is enabled, get the size of the longest index
// to align all the values
var maxIndexLength = options.noAlign ? 0 : Utils.getMaxIndexLength(data);
var key;
var output = [];
Object.getOwnPropertyNames(data).forEach(function(i) {
// Prepend the index at the beginning of the line
key = (i + ': ');
if (!options.noColor) {
key = colors[options.keysColor](key);
}
key = Utils.indent(indentation) + key;
// Skip `undefined`, it's not a valid JSON value.
if (data[i] === undefined) {
return;
}
// If the value is serializable, render it in the same line
if (isSerializable(data[i], false, options)) {
var nextIndentation = options.noAlign ? 0 : maxIndexLength - i.length;
key += renderToArray(data[i], options, nextIndentation)[0];
output.push(key);
// If the index is an array or object, render it in next line
} else {
output.push(key);
output.push.apply(
output,
renderToArray(
data[i],
options,
indentation + options.defaultIndentation
)
);
}
});
return output;
};
// ### Render function
// *Parameters:*
//
// * **`data`**: Data to render
// * **`options`**: Hash with different options to configure the parser
// * **`indentation`**: Base indentation of the parsed output
//
// *Example of options hash:*
//
// {
// emptyArrayMsg: '(empty)', // Rendered message on empty strings
// keysColor: 'blue', // Color for keys in hashes
// dashColor: 'red', // Color for the dashes in arrays
// stringColor: 'grey', // Color for strings
// defaultIndentation: 2 // Indentation on nested objects
// }
exports.render = function render(data, options, indentation) {
// Default values
indentation = indentation || 0;
options = options || {};
options.emptyArrayMsg = options.emptyArrayMsg || '(empty array)';
options.keysColor = options.keysColor || 'green';
options.dashColor = options.dashColor || 'green';
options.numberColor = options.numberColor || 'blue';
options.defaultIndentation = options.defaultIndentation || 2;
options.noColor = !!options.noColor;
options.noAlign = !!options.noAlign;
options.stringColor = options.stringColor || null;
return renderToArray(data, options, indentation).join('\n');
};
// ### Render from string function
// *Parameters:*
//
// * **`data`**: Data to render as a string
// * **`options`**: Hash with different options to configure the parser
// * **`indentation`**: Base indentation of the parsed output
//
// *Example of options hash:*
//
// {
// emptyArrayMsg: '(empty)', // Rendered message on empty strings
// keysColor: 'blue', // Color for keys in hashes
// dashColor: 'red', // Color for the dashes in arrays
// defaultIndentation: 2 // Indentation on nested objects
// }
exports.renderString = function renderString(data, options, indentation) {
var output = '';
var parsedData;
// If the input is not a string or if it's empty, just return an empty string
if (typeof data !== 'string' || data === '') {
return '';
}
// Remove non-JSON characters from the beginning string
if (data[0] !== '{' && data[0] !== '[') {
var beginingOfJson;
if (data.indexOf('{') === -1) {
beginingOfJson = data.indexOf('[');
} else if (data.indexOf('[') === -1) {
beginingOfJson = data.indexOf('{');
} else if (data.indexOf('{') < data.indexOf('[')) {
beginingOfJson = data.indexOf('{');
} else {
beginingOfJson = data.indexOf('[');
}
output += data.substr(0, beginingOfJson) + '\n';
data = data.substr(beginingOfJson);
}
try {
parsedData = JSON.parse(data);
} catch (e) {
// Return an error in case of an invalid JSON
return colors.red('Error:') + ' Not valid JSON!';
}
// Call the real render() method
output += exports.render(parsedData, options, indentation);
return output;
};