feat: stringify json

This commit is contained in:
Ibrahima G. Coulibaly
2025-03-08 07:11:57 +00:00
parent 90d3c0801e
commit f678c76200
9 changed files with 243 additions and 25 deletions

View File

@@ -0,0 +1,28 @@
export const stringifyJson = (
input: string,
indentationType: 'tab' | 'space',
spacesCount: number,
escapeHtml: boolean
): string => {
let parsedInput;
try {
// Safely evaluate the input string as JavaScript
parsedInput = eval('(' + input + ')');
} catch (e) {
throw new Error('Invalid JavaScript object/array');
}
const indent = indentationType === 'tab' ? '\t' : ' '.repeat(spacesCount);
let result = JSON.stringify(parsedInput, null, indent);
if (escapeHtml) {
result = result
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
return result;
};