/** * Attempt to fix common JSON issues and return valid JSON if the result is valid JSON, * otherwise `undefined`. */ export const tryFixJSON = (input: string): string | undefined => { const fixed = removeTrailingCommas(input); try { JSON.parse(fixed); return fixed; } catch { return undefined; } }; /** * Remove trailing commas before `}` and `]` outside of string literals. */ const removeTrailingCommas = (input: string): string => { const toRemove = new Set(); let inString = false; let escape = false; for (let index = 0; index < input.length; index += 1) { const char = input.charAt(index); if (escape) { escape = false; continue; } if (char === '\\' && inString) { escape = true; continue; } if (char === '"') { inString = !inString; continue; } if (!inString && char === ',') { // get the first non-whitespace char after the comma let nextChar = index + 1; while (nextChar < input.length && /\s/u.test(input.charAt(nextChar))) { nextChar += 1; } if ( nextChar < input.length && (input.charAt(nextChar) === '}' || input.charAt(nextChar) === ']') ) { toRemove.add(index); } } } if (toRemove.size === 0) { return input; } let result = ''; for (let index = 0; index < input.length; index += 1) { if (!toRemove.has(index)) { result += input.charAt(index); } } return result; };