pub fn parse_with_schema<T: DeserializeOwned + SchemaInfo>(
input: &str,
) -> Result<T>Expand description
Parses an LLM response using schema information for guided parsing.
This function leverages compile-time schema information from the SchemaInfo trait
to make better parsing decisions. It’s particularly useful for:
- Field name normalization (camelCase → snake_case)
- Better error messages with type context
- Schema-aware type coercion
§Examples
use tryparse::parse_with_schema;
use tryparse::schema::SchemaInfo;
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
user_name: String,
age: u32,
}
// Implement SchemaInfo manually (or use derive macro with feature flag)
impl SchemaInfo for User {
fn schema() -> tryparse::schema::Schema {
tryparse::schema::Schema::Object {
name: "User".to_string(),
fields: vec![
tryparse::schema::Field::new("user_name", tryparse::schema::Schema::String)
.with_alias("userName")
.with_alias("UserName"),
tryparse::schema::Field::new("age", tryparse::schema::Schema::Int),
],
}
}
}
// Parse with camelCase field names - schema guides normalization
let response = r#"{"userName": "Alice", "age": 30}"#;
let user: User = parse_with_schema(response).unwrap();
assert_eq!(user.user_name, "Alice");§Errors
Returns ParseError::NoCandidates if no valid JSON could be extracted.
Returns ParseError::DeserializeFailed if deserialization fails for all candidates.