Struct AsyncJsonLinesReader

Source
pub struct AsyncJsonLinesReader<R> { /* private fields */ }
Available on crate feature async only.
Expand description

A structure for asynchronously reading JSON values from JSON Lines input.

An AsyncJsonLinesReader wraps a tokio::io::AsyncBufRead instance and parses each line as a serde::de::DeserializeOwned value in JSON.

§Example

use futures_util::TryStreamExt;
use serde::Deserialize;
use serde_jsonlines::AsyncJsonLinesReader;
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 reader = AsyncJsonLinesReader::new(fp);
    let items = reader
        .read_all::<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(())
}

Implementations§

Source§

impl<R> AsyncJsonLinesReader<R>

Source

pub fn new(reader: R) -> Self

Construct a new AsyncJsonLinesReader from a tokio::io::AsyncBufRead instance

Source

pub fn into_inner(self) -> R

Consume the AsyncJsonLinesReader and return the underlying reader

Source

pub fn get_ref(&self) -> &R

Get a reference to the underlying reader

Source

pub fn get_mut(&mut self) -> &mut R

Get a mutable reference to the underlying reader

Source

pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R>

Get a pinned mutable reference to the underlying reader

Source§

impl<R: AsyncBufRead> AsyncJsonLinesReader<R>

Source

pub async fn read<T>(&mut self) -> Result<Option<T>>
where T: DeserializeOwned, R: Unpin,

Asynchronously read & deserialize a line of JSON from the underlying reader.

If end-of-file is reached, this method returns Ok(None).

Note that separate calls to this method may read different types of values.

§Errors

Has the same error conditions as tokio::io::AsyncBufReadExt::read_line() and serde_json::from_str(). Note that, in the latter case (which can be identified by the std::io::Error having a serde_json::Error value as its payload), continuing to read from the AsyncJsonLinesReader afterwards will pick up on the next line as though the error never happened, so invalid JSON can be easily ignored if you so wish.

Source

pub fn read_all<T>(self) -> JsonLinesStream<R, T>

Consume the AsyncJsonLinesReader 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. If you wish to read lines of varying types, use the read() method instead.

Trait Implementations§

Source§

impl<R: Clone> Clone for AsyncJsonLinesReader<R>

Source§

fn clone(&self) -> AsyncJsonLinesReader<R>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<R: Debug> Debug for AsyncJsonLinesReader<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<R: PartialEq> PartialEq for AsyncJsonLinesReader<R>

Source§

fn eq(&self, other: &AsyncJsonLinesReader<R>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<R: Eq> Eq for AsyncJsonLinesReader<R>

Source§

impl<R> StructuralPartialEq for AsyncJsonLinesReader<R>

Source§

impl<'__pin, R> Unpin for AsyncJsonLinesReader<R>
where __Origin<'__pin, R>: Unpin,

Auto Trait Implementations§

§

impl<R> Freeze for AsyncJsonLinesReader<R>
where R: Freeze,

§

impl<R> RefUnwindSafe for AsyncJsonLinesReader<R>
where R: RefUnwindSafe,

§

impl<R> Send for AsyncJsonLinesReader<R>
where R: Send,

§

impl<R> Sync for AsyncJsonLinesReader<R>
where R: Sync,

§

impl<R> UnwindSafe for AsyncJsonLinesReader<R>
where R: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.