jsonfm
Version:
JSON format for good presentation
98 lines (83 loc) • 2.49 kB
text/typescript
/*
change for npm modules.
by Luiz Estácio.
json-format v.1.1
http://github.com/phoboslab/json-format
Released under MIT license:
http://www.opensource.org/licenses/mit-license.php
*/
var p: Array<any> = [],
indentConfig = {
tab: { char: '\t', size: 1 },
space: { char: ' ', size: 4 }
},
configDefault = {
type: 'tab'
},
push = function (m: any) { return '\\' + p.push(m) + '\\'; },
pop = function (m: any, i: number) { return p[i - 1] },
tabs = function (count: number, indentType: string | undefined) { return new Array(count + 1).join(indentType); };
function JSONFormat(json: string, indentType: string) {
p = [];
var out = "",
indent = 0;
// Extract backslashes and strings
json = json
.replace(/\\./g, push)
.replace(/(".*?"|'.*?')/g, push)
.replace(/\s+/, '');
// Indent and insert newlines
for (var i = 0; i < json.length; i++) {
var c = json.charAt(i);
switch (c) {
case '{':
case '[':
out += c + "\n" + tabs(++indent, indentType);
break;
case '}':
case ']':
out += "\n" + tabs(--indent, indentType) + c;
break;
case ',':
out += ",\n" + tabs(indent, indentType);
break;
case ':':
out += ": ";
break;
default:
out += c;
break;
}
}
// Strip whitespace from numeric arrays and put backslashes
// and strings back in
out = out
.replace(/\[[\d,\s]+?\]/g, function (m) { return m.replace(/\s/g, ''); })
.replace(/\\(\d+)\\/g, pop) // strings
.replace(/\\(\d+)\\/g, pop); // backslashes in strings
return out;
};
interface jsonfConfig {
type?: 'space' | "tab" | string;
tab?: { char: '\t', size: 1 };
space?: { char: ' ', size: 4 };
[key: string]: { char: string, size: number } | string | undefined;
}
export = function (json: Array<any> | Object | string, config?: jsonfConfig): string {
if (!config) {
config = configDefault;
}
var indent = config.type as string | undefined ? indentConfig[config.type as "tab"] : indentConfig["tab"];
if (indent == null) {
throw new Error('Unrecognized indent type: "' + config.type + '"');
}
// @ts-expect-error
var indentType = new Array((config.size || indent.size) + 1).join(indent.char);
if (typeof json == "string") {
return JSONFormat(json, indentType);
} else
return JSONFormat(JSON.stringify(json), indentType);
}
declare module 'jsonfm' {
export {jsonfConfig}
}