mirror of
https://github.com/iib0011/omni-tools.git
synced 2025-09-23 16:09:30 +02:00
feat: stringify json
This commit is contained in:
28
src/pages/tools/json/stringify/service.ts
Normal file
28
src/pages/tools/json/stringify/service.ts
Normal 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, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
Reference in New Issue
Block a user