@@ -20,14 +20,18 @@ pub fn strip_markdown_json(content: &str) -> &str {
2020
2121 let content_start = open_pos. saturating_add ( 3 ) ;
2222
23- // Find the NEXT occurrence of ``` after the opening block.
24- // This isolates the actual JSON block even if subsequent prose contains code blocks.
25- let Some ( close_pos) = trimmed[ content_start..] . find ( "```" ) else {
23+ // Find the LAST occurrence of ``` in the entire string.
24+ // Using rfind prevents truncation when JSON content contains embedded triple backticks
25+ // (e.g., code snippet fields). The outermost closing fence is always the last one.
26+ let Some ( close_pos) = trimmed. rfind ( "```" ) else {
2627 return trimmed;
2728 } ;
28- let close_pos = close_pos. saturating_add ( content_start) ;
2929
30- // Content between opening ``` (skip past the ```) and closing ```
30+ // rfind must find a position strictly after the opening fence's content start
31+ if close_pos < content_start {
32+ return trimmed;
33+ }
34+
3135 let after_open = & trimmed[ content_start..close_pos] ;
3236
3337 // Skip the language identifier on the first line (e.g. "json", "json5", " json")
@@ -94,6 +98,15 @@ mod tests {
9498 assert_eq ! ( strip_markdown_json( input) , "{\" key\" : \" value\" }" ) ;
9599 }
96100
101+ #[ test]
102+ fn test_embedded_backticks_in_json_content ( ) {
103+ let input = "```json\n {\" code\" : \" ```rust\\ nfn main() {}\\ n```\" }\n ```" ;
104+ assert_eq ! (
105+ strip_markdown_json( input) ,
106+ "{\" code\" : \" ```rust\\ nfn main() {}\\ n```\" }"
107+ ) ;
108+ }
109+
97110 #[ test]
98111 fn test_overlapping_backticks_no_panic ( ) {
99112 let input = "````" ;
0 commit comments