UNPKG

ai-json-fixer

Version:

A simple JSON parser designed to handle malformed JSON from Large Language Models

71 lines 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fixUnescapedQuotes = fixUnescapedQuotes; /** * Fixes unescaped quotes inside JSON strings */ function fixUnescapedQuotes(input) { let result = ''; let inString = false; let escapeNext = false; let stringStartChar = ''; for (let i = 0; i < input.length; i++) { const char = input[i]; // Handle escape sequences if (escapeNext) { result += char; escapeNext = false; continue; } if (char === '\\' && inString) { result += char; escapeNext = true; continue; } // Handle string boundaries if (char === '"' && !inString) { // Starting a new string inString = true; stringStartChar = char; result += char; continue; } if (char === '"' && inString && stringStartChar === '"') { // This could be the end of the string, or an unescaped quote inside // Look ahead to see if this is likely the end of the string // End of string if followed by: }, ], comma, colon, or end of input, or a new JSON key let j = i + 1; while (j < input.length && /\s/.test(input[j])) { j++; } const nextChar = j < input.length ? input[j] : ''; const isStringEnd = nextChar === '' || nextChar === '}' || nextChar === ']' || nextChar === ',' || nextChar === ':' || nextChar === '"'; // New JSON key starting // Also check if this is consecutive quotes (likely all internal quotes except the last) if (i + 1 < input.length && input[i + 1] === '"') { // This is an internal quote followed by another quote result += '\\"'; continue; } if (isStringEnd) { // This is the end of the string inString = false; stringStartChar = ''; result += char; } else { // This is an unescaped quote inside the string result += '\\"'; } continue; } // All other characters result += char; } return result; } //# sourceMappingURL=quote-fixing.js.map