Files
learn-languages/src/utils/json.ts
2026-01-13 23:02:07 +08:00

25 lines
805 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export function parseAIGeneratedJSON<T>(aiResponse: string): T {
// 匹配 ```json ... ``` 包裹的内容
const jsonMatch = aiResponse.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch && jsonMatch[1]) {
try {
return JSON.parse(jsonMatch[1].trim());
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to parse JSON: ${error.message}`);
} else if (typeof error === 'string') {
throw new Error(`Failed to parse JSON: ${error}`);
} else {
throw new Error('Failed to parse JSON: Unknown error');
}
}
}
// 如果没有找到json代码块尝试直接解析整个字符串
try {
return JSON.parse(aiResponse.trim());
} catch (error) {
throw new Error('No valid JSON found in the response');
}
}