@langchain/core
Version:
Core LangChain.js abstractions and schemas
51 lines (49 loc) • 1.82 kB
JavaScript
//#region src/utils/json.ts
function parseJsonMarkdown(s, parser = parsePartialJson) {
s = s.trim();
const firstFenceIndex = s.indexOf("```");
if (firstFenceIndex === -1) return parser(s);
let contentAfterFence = s.substring(firstFenceIndex + 3);
if (contentAfterFence.startsWith("json\n")) contentAfterFence = contentAfterFence.substring(5);
else if (contentAfterFence.startsWith("json")) contentAfterFence = contentAfterFence.substring(4);
else if (contentAfterFence.startsWith("\n")) contentAfterFence = contentAfterFence.substring(1);
const closingFenceIndex = contentAfterFence.indexOf("```");
let finalContent = contentAfterFence;
if (closingFenceIndex !== -1) finalContent = contentAfterFence.substring(0, closingFenceIndex);
return parser(finalContent.trim());
}
function parsePartialJson(s) {
if (typeof s === "undefined") return null;
try {
return JSON.parse(s);
} catch {}
let new_s = "";
const stack = [];
let isInsideString = false;
let escaped = false;
for (let char of s) {
if (isInsideString) if (char === "\"" && !escaped) isInsideString = false;
else if (char === "\n" && !escaped) char = "\\n";
else if (char === "\\") escaped = !escaped;
else escaped = false;
else if (char === "\"") {
isInsideString = true;
escaped = false;
} else if (char === "{") stack.push("}");
else if (char === "[") stack.push("]");
else if (char === "}" || char === "]") if (stack && stack[stack.length - 1] === char) stack.pop();
else return null;
new_s += char;
}
if (isInsideString) new_s += "\"";
for (let i = stack.length - 1; i >= 0; i -= 1) new_s += stack[i];
try {
return JSON.parse(new_s);
} catch {
return null;
}
}
//#endregion
exports.parseJsonMarkdown = parseJsonMarkdown;
exports.parsePartialJson = parsePartialJson;
//# sourceMappingURL=json.cjs.map