Files
Prisma/prisma/utils.ts
从何开始123 54e9bf5906 1
2026-01-08 02:16:42 +08:00

23 lines
775 B
TypeScript

/**
* Cleans a JSON string that might be wrapped in Markdown code blocks or contain explanatory text.
*/
export const cleanJsonString = (str: string) => {
if (!str) return "{}";
// 1. Try to find markdown JSON block
const markdownMatch = str.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
if (markdownMatch && markdownMatch[1]) {
return markdownMatch[1].trim();
}
// 2. Try to find the first '{' and the last '}'
const firstOpen = str.indexOf('{');
const lastClose = str.lastIndexOf('}');
if (firstOpen !== -1 && lastClose !== -1 && lastClose > firstOpen) {
return str.substring(firstOpen, lastClose + 1);
}
// 3. Fallback: return original if it looks like JSON, otherwise empty object
return str.trim().startsWith('{') ? str : "{}";
};