ai-json-fixer
Version:
A simple JSON parser designed to handle malformed JSON from Large Language Models
52 lines • 2.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractFromMarkdown = extractFromMarkdown;
/**
* Extracts JSON content from markdown code blocks or inline code
*/
function extractFromMarkdown(input) {
// Handle empty code blocks first
if (/```(?:json|JSON)?\s*\r?\n\s*\r?\n```/.test(input)) {
return '';
}
// First, try to find triple backtick code blocks with json/JSON identifier
const tripleBacktickJsonPattern = /```(?:json|JSON)\s*\r?\n([\s\S]*?)\r?\n\s*```/g;
let match;
while ((match = tripleBacktickJsonPattern.exec(input)) !== null) {
const content = match[1];
if (content !== undefined) {
// Trim both leading and trailing whitespace
const trimmed = content.trim();
// Return the content without validation - let other fixes handle validation
if (trimmed) {
return trimmed;
}
}
}
// Then try triple backtick blocks without language identifier
const tripleBacktickPattern = /```\s*\r?\n([\s\S]*?)\r?\n\s*```/g;
while ((match = tripleBacktickPattern.exec(input)) !== null) {
const content = match[1];
if (content !== undefined && content.trim()) {
// Check if it looks like JSON
const trimmed = content.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
// Return content that looks like JSON without validation
return trimmed;
}
}
}
// If no triple backtick blocks found, look for inline code that contains JSON
const inlineCodePattern = /`([^`]+)`/g;
while ((match = inlineCodePattern.exec(input)) !== null) {
const content = match[1];
// Check if it looks like JSON (starts with { or [)
if (content && (content.trim().startsWith('{') || content.trim().startsWith('['))) {
// Return content that looks like JSON without validation
return content.trim();
}
}
// If no markdown blocks found, return the original input
return input;
}
//# sourceMappingURL=markdown-extraction.js.map