pub trait JsonlDeserialize {
// Required method
fn deserialize<T>(self) -> impl Stream<Item = Result<T>>
where T: for<'a> Deserialize<'a>;
}Expand description
Extension trait to add deserialization capabilities to JSONL readers.
This trait provides methods to deserialize JSON lines into strongly-typed Rust structures.
It works with any type that implements serde::Deserialize and processes each line
of a JSONL file as a separate JSON object.
§Examples
§Basic Usage with Custom Types
ⓘ
use async_jsonl::{Jsonl, JsonlDeserialize};
use futures::StreamExt;
use serde::Deserialize;
use std::io::Cursor;
#[derive(Deserialize, Debug, PartialEq)]
struct User {
id: u64,
name: String,
email: String,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let data = r#"{"id": 1, "name": "Alice", "email": "alice@example.com"}
{"id": 2, "name": "Bob", "email": "bob@example.com"}"#;
let reader = Jsonl::new(Cursor::new(data.as_bytes()));
let mut user_stream = reader.deserialize::<User>();
while let Some(result) = user_stream.next().await {
match result {
Ok(user) => println!("User: {} ({})", user.name, user.email),
Err(e) => eprintln!("Failed to parse user: {}", e),
}
}
Ok(())
}§Error Handling and Filtering
ⓘ
use async_jsonl::{Jsonl, JsonlDeserialize};
use futures::StreamExt;
use serde::Deserialize;
use std::io::Cursor;
#[derive(Deserialize, Debug)]
struct Product {
name: String,
price: f64,
#[serde(default)]
in_stock: bool,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let data = r#"{"name": "Widget A", "price": 19.99, "in_stock": true}
{"name": "Widget B", "price": 29.99, "in_stock": false}"#;
let reader = Jsonl::new(Cursor::new(data.as_bytes()));
// Filter only successful deserializations and in-stock products
let in_stock_products: Vec<Product> = reader
.deserialize::<Product>()
.filter_map(|result| async move {
match result {
Ok(product) if product.in_stock => Some(product),
Ok(_) => None, // Out of stock
Err(e) => {
eprintln!("Skipping invalid product: {}", e);
None
}
}
})
.collect()
.await;
println!("Found {} products in stock", in_stock_products.len());
Ok(())
}Required Methods§
Sourcefn deserialize<T>(self) -> impl Stream<Item = Result<T>>where
T: for<'a> Deserialize<'a>,
fn deserialize<T>(self) -> impl Stream<Item = Result<T>>where
T: for<'a> Deserialize<'a>,
Deserialize JSON lines into the specified type
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.