try_parse_partial_json

Function try_parse_partial_json 

Source
pub fn try_parse_partial_json(partial_json: &str) -> Result<Option<Value>>
Expand description

Attempt to parse potentially incomplete JSON from a streaming response

This function tries multiple strategies to handle partial JSON:

  1. Parse as-is (might already be valid JSON)
  2. Normalize curly/smart quotes (LLMs sometimes produce these)
  3. Escape unescaped control characters in strings
  4. Extract from markdown code blocks (only if above attempts fail)
  5. Auto-close open structures (for streaming partial responses)

NOTE: Markdown extraction is intentionally done AFTER trying to parse as raw JSON. This prevents issues where valid JSON containing embedded markdown code blocks (e.g., in a string field like message) would be incorrectly extracted.

§Arguments

  • partial_json - The potentially incomplete JSON string

§Returns

  • Ok(Some(JsonValue)) - Successfully parsed (complete or auto-closed)
  • Ok(None) - Cannot parse yet, need more data
  • Err(...) - Unrecoverable parsing error