feat: extract parseJSON()

This commit is contained in:
Li Xin
2025-04-22 11:02:18 +08:00
parent b36f36f530
commit 5ee1632489
5 changed files with 30 additions and 9 deletions
+17
View File
@@ -0,0 +1,17 @@
import { parse } from "best-effort-json-parser";
export function parseJSON<T>(json: string | null | undefined, fallback: T) {
if (!json) {
return fallback;
}
try {
const raw = json
.trim()
.replace(/^```json\s*/, "")
.replace(/^```\s*/, "")
.replace(/\s*```$/, "");
return parse(raw) as T;
} catch {
return fallback;
}
}