forest-express
Version:
Official package for all Forest Express Lianas
52 lines (51 loc) • 2.03 kB
JavaScript
;
var _ = require('lodash');
var prettyPrint = function prettyPrint(json) {
var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var result = '';
if (_.isArray(json)) {
result += '[';
var isSmall = json.length < 3;
var isPrimaryValue = json.length && !_.isArray(json[0]) && !_.isObject(json[0]);
_.each(json, function (item, index) {
if (index === 0 && isPrimaryValue && !isSmall) {
result += "\n".concat(indentation, " ");
} else if (index > 0 && isPrimaryValue && !isSmall) {
result += ",\n".concat(indentation, " ");
} else if (index > 0) {
result += ', ';
}
result += prettyPrint(item, isPrimaryValue ? "".concat(indentation, " ") : indentation);
});
if (isPrimaryValue && !isSmall) {
result += "\n".concat(indentation);
}
result += ']';
} else if (_.isObject(json)) {
result += '{\n';
var isFirst = true;
Object.keys(json).forEach(function (key) {
var value = json[key];
if (!isFirst) {
result += ',\n';
} else {
isFirst = false;
}
result += "".concat(indentation, " \"").concat(key, "\": ");
result += prettyPrint(value, "".concat(indentation, " "));
});
result += "\n".concat(indentation, "}");
} else if (_.isNil(json)) {
result += 'null';
} else if (_.isString(json)) {
// NOTICE: Escape invalid characters (see: https://www.json.org/json-en.html).
// Also, JSON spec precise that '/' doesn't need to be escaped.
// (see: https://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped)
var escapedJsonString = json.replace(/[\\]/g, '\\\\').replace(/["]/g, '\\"').replace(/[\b]/g, '\\b').replace(/[\f]/g, '\\f').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r').replace(/[\t]/g, '\\t');
result += "\"".concat(escapedJsonString, "\"");
} else {
result += "".concat(json);
}
return result;
};
exports.prettyPrint = prettyPrint;