Skip to content

Instantly share code, notes, and snippets.

@t-ski
Last active May 17, 2024 20:19
Show Gist options
  • Save t-ski/a6560a518156f3a5e90a83bad95c0bae to your computer and use it in GitHub Desktop.
Save t-ski/a6560a518156f3a5e90a83bad95c0bae to your computer and use it in GitHub Desktop.
Console-pretty JSON.stringify() alternative for color coded values (atomics and complex objects).
function prettyJSONStringify(value: string) {
const color = (str: string, colorCode: number): string => {
const escape = `\x1b[${
Array.isArray(colorCode)
? `38;2;$${colorCode.join(";")}`
: colorCode
}m`;
return `${escape}${str.replace(/(\x1b\[39m)/g, `$1${escape}`)}\x1b[39m`
};
const format = (value: string): string => {
if (['"undefined"', "null"].includes(value)) {
return color(value.replace(/"/g, ""), 33);
}
if (["true", "false"].includes(value)) {
return color(value, 34);
}
if (/^("|').*\1$/.test(value)) {
return color(value, 35);
}
if (/^\d*(\.\d+)?$/.test(value)) {
return color(value, 36);
}
return `\x1b[2m${value}\x1b[22m`;
};
return JSON.stringify(value, (_, value: unknown) => (value === undefined) ? `${value}` : value, 2)
.split(/\n/g)
.map((line: string) => {
const parts = line.split(/:(.*)/s);
if(!parts[1]) return format(line);
const isTrailing = /,$/.test(parts[1]);
parts[0] = parts[0].slice(0, -1).replace("\"", "");
parts[1] = parts[1].slice(0, parts[1].length - +isTrailing).trim();
return `\x1b[2m${color(
!/^[_\w][_\w\d]*$/.test(parts[0].trimStart())
? `${parts[0].match(/^\s*/)[0]}'${parts[0].trimStart()}'`
: parts[0]
, 33)}:\x1b[22m ${
format(parts[1])
}${isTrailing ? "," : ""}`;
})
.join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment