Source code for lalandre_core.utils.parse_utils

"""
Generic parsing utilities.
"""

import json
from typing import Any, Dict, List, Optional, cast


[docs] def extract_json_object(text: str) -> Optional[Dict[str, Any]]: """Try to extract a JSON object from *text* (which may contain markdown fences). Returns the first valid ``dict`` found, or ``None``. """ raw = (text or "").strip() if not raw: return None # Strip markdown code fences if raw.startswith("```"): raw = "\n".join(line for line in raw.splitlines() if not line.strip().startswith("```")).strip() # Attempt direct parse try: payload = json.loads(raw) if isinstance(payload, dict): return cast(Dict[str, Any], payload) except json.JSONDecodeError: pass # Find the outermost { … } start = raw.find("{") end = raw.rfind("}") if start < 0 or end <= start: return None try: payload = json.loads(raw[start : end + 1]) except json.JSONDecodeError: return None if isinstance(payload, dict): return cast(Dict[str, Any], payload) return None
# --------------------------------------------------------------------------- # Safe type coercions (avoid scattered isinstance checks in service code) # ---------------------------------------------------------------------------
[docs] def as_dict(value: Any) -> Dict[str, Any]: """Return *value* if it is a ``dict``, else an empty ``dict``.""" if isinstance(value, dict): return cast(Dict[str, Any], value) return {}
[docs] def as_optional_dict(value: Any) -> Optional[Dict[str, Any]]: """Return *value* if it is a ``dict``, else ``None``.""" if isinstance(value, dict): return cast(Dict[str, Any], value) return None
[docs] def as_str(value: Any, *, default: str = "") -> str: """Coerce *value* to ``str``.""" if isinstance(value, str): return value if value is None: return default return str(value)
[docs] def as_document_list(value: Any) -> List[Dict[str, Any]]: """Return only the ``dict`` items from *value* (must be a list).""" if not isinstance(value, list): return [] docs: List[Dict[str, Any]] = [] raw_items: List[Any] = cast(List[Any], value) for item in raw_items: if isinstance(item, dict): docs.append(cast(Dict[str, Any], item)) return docs
[docs] def to_optional_int(value: Any) -> Optional[int]: """Convert *value* to ``int`` when possible, else ``None``.""" try: return int(value) if value is not None else None except (TypeError, ValueError): return None
[docs] def sanitize_error_text(error: Exception, *, max_chars: int = 220) -> str: """Return a truncated, safe string representation of *error*.""" text = str(error).strip() or error.__class__.__name__ return text[:max_chars]
[docs] def coerce_bool(value: Any, default: bool) -> bool: """Return *value* if it is already a ``bool``, else *default*.""" if isinstance(value, bool): return value return default
[docs] def coerce_float(value: Any, default: float) -> float: """Return *value* cast to ``float`` when it is numeric, else *default*.""" if isinstance(value, (int, float)): return float(value) return default