append_json_lines

Function append_json_lines 

Source
pub fn append_json_lines<P, I, T>(path: P, items: I) -> Result<()>
where P: AsRef<Path>, I: IntoIterator<Item = T>, T: Serialize,
Expand description

Append an iterator of values to the file at path as JSON Lines.

If the file does not already exist, it is created. If it does exist, the new lines are added after any lines that are already present.

§Errors

Has the same error conditions as File::create(), serde_json::to_writer(), std::io::Write::write_all(), and std::io::Write::flush().

§Example

use serde::Serialize;
use serde_jsonlines::append_json_lines;
use std::fs::read_to_string;

#[derive(Serialize)]
pub struct Structure {
    pub name: String,
    pub size: i32,
    pub on: bool,
}

fn main() -> std::io::Result<()> {
    append_json_lines(
        "example.jsonl",
        [
            Structure {
                name: "Foo Bar".into(),
                size: 42,
                on: true,
            },
            Structure {
                name: "Quux".into(),
                size: 23,
                on: false,
            },
        ],
    )?;
    assert_eq!(
        read_to_string("example.jsonl")?,
        concat!(
            "{\"name\":\"Foo Bar\",\"size\":42,\"on\":true}\n",
            "{\"name\":\"Quux\",\"size\":23,\"on\":false}\n",
        )
    );
    append_json_lines(
        "example.jsonl",
        [
            Structure {
                name: "Gnusto Cleesh".into(),
                size: 17,
                on: true,
            },
            Structure {
                name: "baz".into(),
                size: 69105,
                on: false,
            },
        ],
    )?;
    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",
            "{\"name\":\"baz\",\"size\":69105,\"on\":false}\n",
        )
    );
    Ok(())
}