pub trait AsyncBufReadJsonLines: AsyncBufRead {
// Provided method
fn json_lines<T>(self) -> JsonLinesStream<Self, T>
where Self: Sized { ... }
}
Available on crate feature
async
only.Expand description
An extension trait for the tokio::io::AsyncBufRead
trait that adds a
json_lines()
method
§Example
use futures_util::TryStreamExt;
use serde::Deserialize;
use serde_jsonlines::AsyncBufReadJsonLines;
use tokio::fs::{write, File};
use tokio::io::BufReader;
#[derive(Debug, Deserialize, PartialEq)]
pub struct Structure {
pub name: String,
pub size: i32,
pub on: bool,
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
write(
"example.jsonl",
concat!(
"{\"name\": \"Foo Bar\", \"on\":true,\"size\": 42 }\n",
"{ \"name\":\"Quux\", \"on\" : false ,\"size\": 23}\n",
" {\"name\": \"Gnusto Cleesh\" , \"on\": true, \"size\": 17}\n",
),
)
.await?;
let fp = BufReader::new(File::open("example.jsonl").await?);
let items = fp
.json_lines::<Structure>()
.try_collect::<Vec<_>>()
.await?;
assert_eq!(
items,
[
Structure {
name: "Foo Bar".into(),
size: 42,
on: true,
},
Structure {
name: "Quux".into(),
size: 23,
on: false,
},
Structure {
name: "Gnusto Cleesh".into(),
size: 17,
on: true,
},
]
);
Ok(())
}
Provided Methods§
Sourcefn json_lines<T>(self) -> JsonLinesStream<Self, T>where
Self: Sized,
fn json_lines<T>(self) -> JsonLinesStream<Self, T>where
Self: Sized,
Consume the reader and return an asynchronous stream over the deserialized JSON values from each line.
The returned stream has an Item
type of std::io::Result<T>
. Each
call to next()
has the same error conditions as
read()
.
Note that all deserialized values will be of the same type.