pub struct JsonLinesWriter<W> { /* private fields */ }
Expand description
A structure for writing JSON values as JSON Lines.
A JsonLinesWriter
wraps a std::io::Write
instance and writes
serde::Serialize
values to it by serializing each one as a single line
of JSON and appending a newline.
§Example
use serde::Serialize;
use serde_jsonlines::JsonLinesWriter;
use std::fs::{read_to_string, File};
#[derive(Serialize)]
pub struct Structure {
pub name: String,
pub size: i32,
pub on: bool,
}
fn main() -> std::io::Result<()> {
{
let fp = File::create("example.jsonl")?;
let mut writer = JsonLinesWriter::new(fp);
writer.write_all([
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,
},
])?;
writer.flush()?;
}
// End the block to close the writer
assert_eq!(
read_to_string("example.jsonl")?,
concat!(
"{\"name\":\"Foo Bar\",\"size\":42,\"on\":true}\n",
"{\"name\":\"Quux\",\"size\":23,\"on\":false}\n",
"{\"name\":\"Gnusto Cleesh\",\"size\":17,\"on\":true}\n",
)
);
Ok(())
}
Implementations§
Source§impl<W> JsonLinesWriter<W>
impl<W> JsonLinesWriter<W>
Sourcepub fn new(writer: W) -> Self
pub fn new(writer: W) -> Self
Construct a new JsonLinesWriter
from a std::io::Write
instance
Sourcepub fn into_inner(self) -> W
pub fn into_inner(self) -> W
Consume the JsonLinesWriter
and return the underlying writer
Source§impl<W: Write> JsonLinesWriter<W>
impl<W: Write> JsonLinesWriter<W>
Sourcepub fn write<T>(&mut self, value: &T) -> Result<()>
pub fn write<T>(&mut self, value: &T) -> Result<()>
Serialize a value as a line of JSON and write it to the underlying writer, followed by a newline.
Note that separate calls to this method may write different types of values.
§Errors
Has the same error conditions as serde_json::to_writer()
and
std::io::Write::write_all()
.
Sourcepub fn write_all<T, I>(&mut self, items: I) -> Result<()>where
I: IntoIterator<Item = T>,
T: Serialize,
pub fn write_all<T, I>(&mut self, items: I) -> Result<()>where
I: IntoIterator<Item = T>,
T: Serialize,
Sourcepub fn flush(&mut self) -> Result<()>
pub fn flush(&mut self) -> Result<()>
Flush the underlying writer.
Neither write()
nor
write_all()
flush the writer, so you
must explicitly call this method if you need output flushed.
§Errors
Has the same error conditions as std::io::Write::flush()
.
Trait Implementations§
Source§impl<W: Clone> Clone for JsonLinesWriter<W>
impl<W: Clone> Clone for JsonLinesWriter<W>
Source§fn clone(&self) -> JsonLinesWriter<W>
fn clone(&self) -> JsonLinesWriter<W>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more