From 370a5a62b0d5d5eece36eecb58441ce19d1b2a5b Mon Sep 17 00:00:00 2001 From: dadaloop82 Date: Sun, 10 May 2026 15:02:58 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20robust=20JSON=20extraction=20in=20chatTo?= =?UTF-8?q?Recipe=20=E2=80=94=20handles=20Gemini=20preamble=20text=20+=20n?= =?UTF-8?q?ested=20fences?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/index.php | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/api/index.php b/api/index.php index 0e5f1ee..50462fb 100644 --- a/api/index.php +++ b/api/index.php @@ -3661,9 +3661,18 @@ PROMPT; return; } - $text = preg_replace('/^```(?:json)?\s*/i', '', $text); - $text = preg_replace('/\s*```$/i', '', $text); - $text = trim($text); + // Strip markdown code fences (handles ```json ... ``` anywhere in the response) + $text = preg_replace('/```(?:json)?\s*/i', '', $text); + $text = str_replace('```', '', $text); + + // Extract the first complete JSON object from the text (ignores any preamble text) + $start = strpos($text, '{'); + $end = strrpos($text, '}'); + if ($start === false || $end === false || $end <= $start) { + echo json_encode(['success' => false, 'error' => 'parse_error', 'raw' => mb_substr($text, 0, 500)]); + return; + } + $text = substr($text, $start, $end - $start + 1); $recipe = json_decode($text, true); if (!is_array($recipe) || empty($recipe['title'])) {