MCPcopy Create free account
hub / github.com/IBM/AssetOpsBench / _parse_json

Function _parse_json

src/agent/plan_execute/executor.py:225–251  ·  view source on GitHub ↗

Extract a JSON object from an LLM response, with markdown fence handling. Returns the parsed dict, or None if no JSON object could be extracted. An empty dict ``{}`` is a valid successful parse (e.g. for no-arg tools).

(raw: str)

Source from the content-addressed store, hash-verified

223
224
225def _parse_json(raw: str) -> dict | None:
226 """Extract a JSON object from an LLM response, with markdown fence handling.
227
228 Returns the parsed dict, or None if no JSON object could be extracted.
229 An empty dict ``{}`` is a valid successful parse (e.g. for no-arg tools).
230 """
231 text = raw.strip()
232 if text.startswith("```"):
233 lines = text.splitlines()
234 inner = lines[1:-1] if lines[-1].strip() == "```" else lines[1:]
235 text = "\n".join(inner).lstrip("json").strip()
236 try:
237 result = json.loads(text)
238 if isinstance(result, dict):
239 return result
240 except json.JSONDecodeError:
241 pass
242 start, end = text.find("{"), text.rfind("}") + 1
243 if start != -1 and end > start:
244 try:
245 result = json.loads(text[start:end])
246 if isinstance(result, dict):
247 return result
248 except json.JSONDecodeError:
249 pass
250 _log.debug("_parse_json: could not extract a JSON object from: %r…", raw[:120])
251 return None
252
253
254# ── MCP protocol helpers ──────────────────────────────────────────────────────

Calls 1

findMethod · 0.45