Skip to main content

parse_json

Function parse_json 

Source
pub fn parse_json<T: DeserializeOwned>(response: &str) -> Result<T, ParseError>
Expand description

Parse an LLM response into a typed struct.

Strategies (in order):

  1. Direct deserialize on preprocessed text
  2. Extract from markdown code block (```json)
  3. Extract from any code block
  4. Bracket-match a JSON object ({...})
  5. Bracket-match a JSON array ([...])
  6. 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");