Strip Markdown Code Fences Around JSON

Basics
BasicsStructured OutputJSONOpenAIAnthropicGoogle

Problem

LLMs frequently wrap JSON replies in markdown code fences such as ```json ... ```. Implement parse_fenced_json(raw) that strips optional leading/trailing markdown fences (case-insensitive) and whitespace, then parses and returns the Python dict.

Why It Matters: Even with JSON-mode prompts, models often emit triple-backtick wrappers; stripping fences defensively prevents needless JSONDecodeError crashes in production agents.

Function Signature

import json
import re

def parse_fenced_json(raw: str) -> dict:
    """Strip optional markdown code fences and parse JSON into a dict."""

Sample Input & Output

Example 1: Fenced JSON Block

Input:

raw = "```json\n{\"tool\": \"search\", \"top_k\": 3}\n```"

Expected Output:

{"tool": "search", "top_k": 3}

Explanation: Strips the opening ```json and closing ``` before calling json.loads.

Example 2: Already Clean JSON String

Input:

raw = '  {"status": "ok"}  '

Expected Output:

{"status": "ok"}

Explanation: Plain JSON without fences passes through seamlessly after .strip().

Constraints & Edge Cases

  • Must handle both fenced and plain JSON strings.
  • Handle uppercase/lowercase fence tags (json, JSON) or bare ``` fences.
  • Return the parsed Python dict.

Constraints & Evaluation Criteria

  • Must handle both fenced and plain JSON strings.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
```json\n{"status":"ok"}\n```
Expected Output / Criteria
{'status': 'ok'}