Coverage

97%
82
80
2

lib/prettyjson.js

97%
73
71
2
LineHitsSource
1// Package for formatting JSON data in a coloured
2// YAML-style, perfect for CLI output
3
4// ### Export package
51module.exports = exports;
6
7
8// ### Module dependencies
91var colors = require('colors');
101var Utils = require('./utils');
111var fs = require('fs');
12
13// ### Package version
141exports.version = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version;
15
16// ### Render function
17// *Parameters:*
18//
19// * **`data`**: Data to render
20// * **`options`**: Hash with different options to configure the parser
21// * **`indentation`**: Base indentation of the parsed output
22//
23// *Example of options hash:*
24//
25// {
26// emptyArrayMsg: '(empty)', // Rendered message on empty strings
27// keysColor: 'blue', // Color for keys in hashes
28// dashColor: 'red', // Color for the dashes in arrays
29// stringColor: 'grey', // Color for strings
30// defaultIndentation: 2 // Indentation on nested objects
31// }
321exports.render = function render(data, options, indentation) {
33 "use strict";
34
35 // Default value for the indentation param
3665 indentation = indentation || 0;
37
38 // Default values for the options
3965 options = options || {};
4065 options.emptyArrayMsg = options.emptyArrayMsg || '(empty array)';
4165 options.keysColor = options.keysColor || "green";
4265 options.dashColor = options.dashColor || "green";
4365 options.defaultIndentation = options.defaultIndentation || 2;
44
4565 options.stringColor = options.stringColor || null;
46
47 // Initialize the output (it's an array of lines)
4865 var output = [];
49
50 // Helper function to detect if an object can be serializable directly
5165 var isSerializable = function(input) {
5294 if (typeof input === 'string' || typeof input === 'boolean' ||
53 typeof input === 'number' || input === null) {
5464 return true;
55 }
5630 return false;
57 };
58
5965 var addColorToData = function(input) {
6041 if (typeof input === 'string') {
61 // Print strings in regular terminal color
6237 return options.stringColor ? input[options.stringColor] : input;
63 }
64
654 if (input === true) {
661 return (input+'').green;
67 }
683 if (input === false) {
691 return (input+'').red;
70 }
712 if (input === null) {
721 return (input+'').grey;
73 }
741 if (typeof input === 'number') {
751 return (input+'').blue;
76 }
770 return (input+'');
78 };
79
80 // Render a string exactly equal
8165 if (isSerializable(data)) {
8241 output.push(Utils.indent(indentation) + addColorToData(data));
83 }
8424 else if (Array.isArray(data)) {
85 // If the array is empty, render the `emptyArrayMsg`
869 if (data.length === 0) {
872 output.push(Utils.indent(indentation) + options.emptyArrayMsg);
88 } else {
897 data.forEach(function(element) {
90 // Prepend the dash at the begining of each array's element line
9114 var line = Utils.indent(indentation) + ('- ')[options.dashColor];
92
93 // If the element of the array is a string, render it in the same line
9414 if (typeof element === 'string') {
9512 line += exports.render(element, options);
9612 output.push(line);
97
98 // If the element of the array is an array or object, render it in next line
99 } else {
1002 output.push(line);
1012 output.push(
102 exports.render(element, options, indentation + options.defaultIndentation)
103 );
104 }
105 });
106 }
107 }
10815 else if (typeof data === 'object') {
109 // Get the size of the longest index to render all the values on the same column
11015 var maxIndexLength = Utils.getMaxIndexLength(data);
11115 var key;
112
11315 for(var i in data) {
11430 if (data.hasOwnProperty(i)) {
115 // Prepend the index at the beginning of the line
11629 key = Utils.indent(indentation) + (i + ': ')[options.keysColor];
117
118 // If the value is serializable, render it in the same line
11929 if (isSerializable(data[i])) {
12023 key += exports.render(data[i], options, maxIndexLength - i.length);
12123 output.push(key);
122
123 // If the index is an array or object, render it in next line
124 } else {
1256 output.push(key);
1266 output.push(
127 exports.render(data[i], options, indentation + options.defaultIndentation)
128 );
129 }
130 }
131 }
132 }
133 // Return all the lines as a string
13465 return output.join('\n');
135};
136
137// ### Render from string function
138// *Parameters:*
139//
140// * **`data`**: Data to render as a string
141// * **`options`**: Hash with different options to configure the parser
142// * **`indentation`**: Base indentation of the parsed output
143//
144// *Example of options hash:*
145//
146// {
147// emptyArrayMsg: '(empty)', // Rendered message on empty strings
148// keysColor: 'blue', // Color for keys in hashes
149// dashColor: 'red', // Color for the dashes in arrays
150// defaultIndentation: 2 // Indentation on nested objects
151// }
1521exports.renderString = function renderString(data, options, indentation) {
153 "use strict";
154
1557 var output = '';
1567 var parsedData;
157 // If the input is not a string or if it's empty, just return an empty string
1587 if (typeof data !== 'string' || data === '') {
1592 return '';
160 }
161
162 // Remove non-JSON characters from the beginning string
1635 if (data[0] !== '{' && data[0] !== '[') {
1643 var beginingOfJson;
1653 if (data.indexOf('{') === -1) {
1662 beginingOfJson = data.indexOf('[');
1671 } else if (data.indexOf('[') === -1) {
1681 beginingOfJson = data.indexOf('{');
169 } else {
1700 beginingOfJson = data.indexOf('{') < data.indexOf('[') ? data.indexOf('{') : data.indexOf('[');
171 }
1723 output += data.substr(0, beginingOfJson) + "\n";
1733 data = data.substr(beginingOfJson);
174 }
175
1765 try {
1775 parsedData = JSON.parse(data);
178 } catch (e) {
179 // Return an error in case of an invalid JSON
1801 return 'Error:'.red + ' Not valid JSON!';
181 }
182
183 // Call the real render() method
1844 output += exports.render(parsedData, options);
1854 return output;
186};
187

lib/utils.js

100%
9
9
0
LineHitsSource
1"use strict";
2
3/**
4 * Creates a string with the same length as `numSpaces` parameter
5 **/
61exports.indent = function indent(numSpaces) {
786 return new Array(numSpaces+1).join(' ');
8};
9
10/**
11 * Gets the string length of the longer index in a hash
12 **/
131exports.getMaxIndexLength = function(input) {
1415 var maxWidth = 0;
1515 var key;
16
1715 for (key in input) {
1830 if (input.hasOwnProperty(key) && key.length > maxWidth) {
1920 maxWidth = key.length;
20 }
21 }
2215 return maxWidth;
23};
24