30 lines
964 B
JavaScript
30 lines
964 B
JavaScript
/**
|
|
* parseAiJson
|
|
* Attempts to extract a JSON array or object from a string that may include
|
|
* extra text or a fenced code block (```json ... ```).
|
|
*
|
|
* @param {string} rawText - The raw string from the AI response.
|
|
* @returns {any} - The parsed JSON (object or array).
|
|
* @throws Will throw an error if parsing fails.
|
|
*/
|
|
function parseAIJson(rawText) {
|
|
if (!rawText || typeof rawText !== 'string') {
|
|
throw new Error('No valid text provided for parseAiJson.');
|
|
}
|
|
|
|
// 1) Look for a fenced code block with "```json" ... "```"
|
|
const fencedRegex = /```json\s*([\s\S]*?)\s*```/i;
|
|
const match = rawText.match(fencedRegex);
|
|
if (match && match[1]) {
|
|
// parse the fenced code block
|
|
const jsonStr = match[1].trim();
|
|
return JSON.parse(jsonStr);
|
|
}
|
|
|
|
// 2) Fallback: try parsing the entire string directly
|
|
// Sometimes the AI might return just a raw JSON array without fences
|
|
return JSON.parse(rawText);
|
|
}
|
|
|
|
export default parseAIJson;
|