mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-20 21:23:08 +03:00
fix(json-viewer): unescape JSON strings in a single pass
Unescaping backslashes before `\n`, `\t` and friends decoded escaped backslashes twice: `\\n` in an escaped JSON string became a raw newline instead of `\n`, so parsing failed with "invalid character". A single replace with a lookup table decodes each escape exactly once. Fixes the CodeQL js/double-escaping alert. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b688f528bd
commit
9b655473bc
2 files changed
+21
-10
No files matched your search
@@ -83,6 +83,13 @@ describe('json models', () => {
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('does not unescape an escaped backslash twice', () => {
|
||||
const escapedJson = '{\\"text\\":\\"line1\\\\nline2\\",\\"path\\":\\"C:\\\\\\\\new\\"}';
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: true, indentSize: 2 });
|
||||
const expected = '{\n "path": "C:\\\\new",\n "text": "line1\\nline2"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('handles single-quoted outer strings', () => {
|
||||
const escapedJson = '\'{\\\"id\\\":\\\"123\\\"}\'';
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: true, indentSize: 2 });
|
||||
|
||||
@@ -28,6 +28,17 @@ function unescapeUnicodeJSON(str: string) {
|
||||
return str.replace(/\\u([\dA-Fa-f]{4})/g, (match, grp) => String.fromCharCode(Number.parseInt(grp, 16)));
|
||||
}
|
||||
|
||||
const JSON_STRING_ESCAPES: Record<string, string> = {
|
||||
'"': '"',
|
||||
'\\': '\\',
|
||||
'/': '/',
|
||||
n: '\n',
|
||||
r: '\r',
|
||||
t: '\t',
|
||||
f: '\f',
|
||||
b: '\b',
|
||||
};
|
||||
|
||||
function unescapeJson(jsonString: string): string {
|
||||
try {
|
||||
// First, try to handle double-escaped scenarios
|
||||
@@ -40,16 +51,9 @@ function unescapeJson(jsonString: string): string {
|
||||
result = result.slice(1, -1);
|
||||
}
|
||||
|
||||
// Handle common escape sequences
|
||||
result = result
|
||||
.replace(/\\"/g, '"') // Unescape quotes
|
||||
.replace(/\\\\/g, '\\') // Unescape backslashes (do this after quotes!)
|
||||
.replace(/\\n/g, '\n') // Unescape newlines
|
||||
.replace(/\\r/g, '\r') // Unescape carriage returns
|
||||
.replace(/\\t/g, '\t') // Unescape tabs
|
||||
.replace(/\\f/g, '\f') // Unescape form feeds
|
||||
.replace(/\\b/g, '\b') // Unescape backspaces
|
||||
.replace(/\\\//g, '/'); // Unescape forward slashes
|
||||
// Handle common escape sequences in a single pass, so an escaped backslash
|
||||
// is not unescaped twice: `\\\\n` becomes `\\n`, not a newline
|
||||
result = result.replace(/\\(["\\/nrtfb])/g, (_, char: string) => JSON_STRING_ESCAPES[char]);
|
||||
|
||||
return result;
|
||||
} catch {
|
||||
|
||||
Reference in new issue
Block a user