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

@@ -1,4 +1,5 @@
import { tool as jsonPrettify } from './prettify/meta';
import { tool as jsonMinify } from './minify/meta';
import { tool as jsonStringify } from './stringify/meta';
export const jsonTools = [jsonPrettify, jsonMinify];
export const jsonTools = [jsonPrettify, jsonMinify, jsonStringify];

View File

@@ -5,8 +5,9 @@ export const tool = defineTool('json', {
name: 'Minify JSON',
path: 'minify',
icon: 'lets-icons:json-light',
description: 'Minify your JSON by removing all unnecessary whitespace and formatting. This tool compresses JSON data to its smallest possible size while maintaining valid JSON structure.',
shortDescription: 'Remove all unnecessary whitespace from JSON data.',
description:
'Minify your JSON by removing all unnecessary whitespace and formatting. This tool compresses JSON data to its smallest possible size while maintaining valid JSON structure.',
shortDescription: 'Quickly compress JSON file.',
keywords: ['minify', 'compress', 'minimize', 'json', 'compact'],
component: lazy(() => import('./index'))
});

View File

@@ -15,7 +15,7 @@ import { FormikProps } from 'formik';
import { ToolComponentProps } from '@tools/defineTool';
import RadioWithTextField from '@components/options/RadioWithTextField';
import SimpleRadio from '@components/options/SimpleRadio';
import { isNumber } from '../../../../utils/string';
import { isNumber, updateNumberField } from '../../../../utils/string';
type InitialValuesType = {
indentationType: 'tab' | 'space';
@@ -141,7 +141,7 @@ export default function PrettifyJson({ title }: ToolComponentProps) {
value={values.spacesCount.toString()}
onRadioClick={() => updateField('indentationType', 'space')}
onTextChange={(val) =>
isNumber(val) ? updateField('spacesCount', Number(val)) : null
updateNumberField(val, 'spacesCount', updateField)
}
/>
<SimpleRadio

View File

@@ -0,0 +1,157 @@
import { Box } from '@mui/material';
import React, { useState } from 'react';
import ToolContent from '@components/ToolContent';
import ToolTextInput from '@components/input/ToolTextInput';
import ToolTextResult from '@components/result/ToolTextResult';
import { stringifyJson } from './service';
import { ToolComponentProps } from '@tools/defineTool';
import RadioWithTextField from '@components/options/RadioWithTextField';
import SimpleRadio from '@components/options/SimpleRadio';
import CheckboxWithDesc from '@components/options/CheckboxWithDesc';
import { isNumber, updateNumberField } from '@utils/string';
import { CardExampleType } from '@components/examples/ToolExamples';
type InitialValuesType = {
indentationType: 'tab' | 'space';
spacesCount: number;
escapeHtml: boolean;
};
const initialValues: InitialValuesType = {
indentationType: 'space',
spacesCount: 2,
escapeHtml: false
};
const exampleCards: CardExampleType<InitialValuesType>[] = [
{
title: 'Simple Object to JSON',
description: 'Convert a basic JavaScript object into a JSON string.',
sampleText: `{ name: "John", age: 30 }`,
sampleResult: `{
"name": "John",
"age": 30
}`,
sampleOptions: {
indentationType: 'space',
spacesCount: 2,
escapeHtml: false
}
},
{
title: 'Array with Mixed Types',
description:
'Convert an array containing different types of values into JSON.',
sampleText: `[1, "hello", true, null, { x: 10 }]`,
sampleResult: `[
1,
"hello",
true,
null,
{
"x": 10
}
]`,
sampleOptions: {
indentationType: 'space',
spacesCount: 4,
escapeHtml: false
}
},
{
title: 'HTML-Escaped JSON',
description: 'Convert an object to JSON with HTML characters escaped.',
sampleText: `{
html: "<div>Hello & Welcome</div>",
message: "Special chars: < > & ' \\""
}`,
sampleResult: `{
&quot;html&quot;: &quot;&lt;div&gt;Hello &amp; Welcome&lt;/div&gt;&quot;,
&quot;message&quot;: &quot;Special chars: &lt; &gt; &amp; &#039; &quot;&quot;
}`,
sampleOptions: {
indentationType: 'space',
spacesCount: 2,
escapeHtml: true
}
}
];
export default function StringifyJson({ title }: ToolComponentProps) {
const [input, setInput] = useState<string>('');
const [result, setResult] = useState<string>('');
const compute = (values: InitialValuesType, input: string) => {
if (input) {
setResult(
stringifyJson(
input,
values.indentationType,
values.spacesCount,
values.escapeHtml
)
);
}
};
return (
<ToolContent
title={title}
input={input}
setInput={setInput}
initialValues={initialValues}
compute={compute}
exampleCards={exampleCards}
inputComponent={
<ToolTextInput
title="JavaScript Object/Array"
value={input}
onChange={setInput}
/>
}
resultComponent={<ToolTextResult title="JSON String" value={result} />}
getGroups={({ values, updateField }) => [
{
title: 'Indentation',
component: (
<Box>
<RadioWithTextField
checked={values.indentationType === 'space'}
title="Use Spaces"
fieldName="indentationType"
description="Indent output with spaces"
value={values.spacesCount.toString()}
onRadioClick={() => updateField('indentationType', 'space')}
onTextChange={(val) =>
updateNumberField(val, 'spacesCount', updateField)
}
/>
<SimpleRadio
onClick={() => updateField('indentationType', 'tab')}
checked={values.indentationType === 'tab'}
description="Indent output with tabs"
title="Use Tabs"
/>
</Box>
)
},
{
title: 'Options',
component: (
<CheckboxWithDesc
checked={values.escapeHtml}
onChange={(value) => updateField('escapeHtml', value)}
title="Escape HTML Characters"
description="Convert HTML special characters to their entity references"
/>
)
}
]}
toolInfo={{
title: 'What Is JSON Stringify?',
description:
'JSON Stringify is a tool that converts JavaScript objects and arrays into their JSON string representation. It properly formats the output with customizable indentation and offers the option to escape HTML special characters, making it safe for web usage. This tool is particularly useful when you need to serialize data structures for storage or transmission, or when you need to prepare JSON data for HTML embedding.'
}}
/>
);
}

View File

@@ -0,0 +1,12 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('json', {
name: 'Stringify JSON',
path: 'stringify',
icon: 'lets-icons:json-format-light',
description: 'Convert JavaScript objects and arrays into their JSON string representation. Options include custom indentation and HTML character escaping for web-safe JSON strings.',
shortDescription: 'Convert JavaScript objects to JSON strings',
keywords: ['stringify', 'serialize', 'convert', 'object', 'array', 'json', 'string'],
component: lazy(() => import('./index'))
});

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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
return result;
};

View File

@@ -1,3 +1,5 @@
import { UpdateField } from '@components/options/ToolOptions';
export function capitalizeFirstLetter(string: string | undefined) {
if (!string) return '';
return string.charAt(0).toUpperCase() + string.slice(1);
@@ -7,6 +9,20 @@ export function isNumber(number: any) {
return !isNaN(parseFloat(number)) && isFinite(number);
}
export const updateNumberField = <T>(
val: string,
key: keyof T,
updateField: UpdateField<T>
) => {
if (val === '') {
// @ts-ignore
updateField(key, '');
} else if (isNumber(val)) {
// @ts-ignore
updateField(key, Number(val));
}
};
export const replaceSpecialCharacters = (str: string) => {
return str
.replace(/\\"/g, '"')