json2jsonl/
json2jsonl.rs

1use anyhow::{anyhow, Context, Result as AnyResult};
2use serde::{Deserialize, Serialize};
3use serdeio::{read_record_from_file, write_records_to_writer, DataFormat};
4
5#[derive(Debug, Deserialize, Serialize)]
6struct User {
7    id: u32,
8    name: String,
9    items: Vec<String>,
10}
11
12pub fn main() -> AnyResult<()> {
13    // get input file path from argv
14    let args: Vec<String> = std::env::args().collect();
15    let input_file_path = &args[1];
16
17    // read json to memory
18    let users: Vec<User> = read_record_from_file(input_file_path)
19        .map_err(|e| anyhow! {e})
20        .context("Failed to read records from file")?;
21
22    // write to stdout in json lines format
23    let writer = std::io::stdout();
24    write_records_to_writer(writer, DataFormat::JsonLines, &users).unwrap();
25
26    Ok(())
27}