pub fn parse_json<T: DeserializeOwned>(response: &str) -> Result<T, ParseError>Expand description
Parse an LLM response into a typed struct.
Strategies (in order):
- Direct deserialize on preprocessed text
- Extract from markdown code block (
```json) - Extract from any code block
- Bracket-match a JSON object (
{...}) - Bracket-match a JSON array (
[...]) - Repair malformed JSON then retry strategies 1-5
§Errors
Returns ParseError::EmptyResponse if input is empty after preprocessing,
ParseError::DeserializationFailed if JSON was found but doesn’t match T.
§Examples
use serde::Deserialize;
use llm_output_parser::parse_json;
#[derive(Deserialize, Debug, PartialEq)]
struct Analysis {
sentiment: String,
confidence: f64,
}
let response = r#"<think>analyzing...</think>{"sentiment": "positive", "confidence": 0.92}"#;
let result: Analysis = parse_json(response).unwrap();
assert_eq!(result.sentiment, "positive");