From 53b0ddf23ad04e5a32e62da4a0e8659d70a2f6ea Mon Sep 17 00:00:00 2001 From: star7th Date: Sat, 12 Apr 2025 10:04:20 +0800 Subject: [PATCH] =?UTF-8?q?json=E5=8F=8D=E8=BD=AC=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/tools/json_formatter/page.tsx | 81 ++++++++++++++++++++++ src/config/i18n/tools/json_formatter/en.ts | 5 +- src/config/i18n/tools/json_formatter/zh.ts | 5 +- 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/app/tools/json_formatter/page.tsx b/src/app/tools/json_formatter/page.tsx index eb4f0f7..d2fb642 100644 --- a/src/app/tools/json_formatter/page.tsx +++ b/src/app/tools/json_formatter/page.tsx @@ -211,6 +211,66 @@ export default function JsonFormatter() { } }; + // 字符串转义 + const escapeString = () => { + if (!jsonInput) return; + + try { + // 将常见字符转义为JSON字符串中的格式 + const processed = jsonInput + .replace(/\\/g, '\\\\') // 先转义反斜杠 + .replace(/"/g, '\\"') // 转义双引号 + .replace(/\n/g, '\\n') // 转义换行符 + .replace(/\r/g, '\\r') // 转义回车符 + .replace(/\t/g, '\\t') // 转义制表符 + .replace(/\f/g, '\\f') // 转义换页符 + .replace(/\b/g, '\\b'); // 转义退格符 + + // 检查是否有变化 + if (processed === jsonInput) { + console.log('没有检测到需要转义的内容'); + return; + } + + // 更新输入框 + setJsonInput(processed); + + // 不需要立即格式化,因为用户可能还需要进一步编辑 + } catch (error) { + console.error('字符串转义处理失败:', error); + } + }; + + // 字符串反转义 + const unescapeString = () => { + if (!jsonInput) return; + + try { + // 将JSON字符串中的转义字符还原为原始字符 + const processed = jsonInput + .replace(/\\"/g, '"') // 反转义双引号 + .replace(/\\n/g, '\n') // 反转义换行符 + .replace(/\\r/g, '\r') // 反转义回车符 + .replace(/\\t/g, '\t') // 反转义制表符 + .replace(/\\f/g, '\f') // 反转义换页符 + .replace(/\\b/g, '\b') // 反转义退格符 + .replace(/\\\\/g, '\\'); // 最后反转义反斜杠 + + // 检查是否有变化 + if (processed === jsonInput) { + console.log('没有检测到需要反转义的内容'); + return; + } + + // 更新输入框 + setJsonInput(processed); + + // 不需要立即格式化,因为用户可能还需要进一步编辑 + } catch (error) { + console.error('字符串反转义处理失败:', error); + } + }; + // 复制结果到剪贴板 const copyToClipboard = () => { if (jsonOutput) { @@ -794,6 +854,26 @@ export default function JsonFormatter() { {t('tools.json_formatter.remove_slash')} + {/* 字符串转义按钮 */} + + + {/* 字符串反转义按钮 */} + + {isLoading && (