Fix JSON parsing when Claude returns text preamble before menu JSON

The Claude API sometimes returns explanatory text before the JSON
response even when instructed to return only JSON. Added extraction
logic to find the first { character and strip any leading text.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
John Mizerek 2026-03-01 10:30:21 -08:00
parent 9acf4aa511
commit ced4082993

View file

@ -1180,6 +1180,7 @@
<!--- Clean up JSON response --->
<cfset responseText = trim(responseText)>
<!--- Strip markdown code fences --->
<cfif left(responseText, 7) EQ "```json">
<cfset responseText = mid(responseText, 8, len(responseText) - 7)>
</cfif>
@ -1190,6 +1191,18 @@
<cfset responseText = left(responseText, len(responseText) - 3)>
</cfif>
<cfset responseText = trim(responseText)>
<!--- If response doesn't start with {, extract JSON object from text --->
<cfif left(responseText, 1) NEQ "{">
<cfset jsonStart = find("{", responseText)>
<cfif jsonStart GT 0>
<cfset responseText = mid(responseText, jsonStart, len(responseText) - jsonStart + 1)>
<!--- Strip any trailing text/fences after the JSON --->
<cfif right(trim(responseText), 3) EQ "```">
<cfset responseText = left(trim(responseText), len(trim(responseText)) - 3)>
</cfif>
<cfset responseText = trim(responseText)>
</cfif>
</cfif>
<!--- Remove trailing commas before ] or } --->
<cfset responseText = reReplace(responseText, ",(\s*[\]\}])", "\1", "all")>
<!--- Remove control characters that break JSON --->