Parse in-memory CSV string into StringRecords and structs



examples/csv/parse-csv-string/src/main.rs
#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct Fruit {
    fruit: String,
    color: String,
    peal: String,
}

fn main() {
    let csv_text = "
fruit,color,peal
apple,red,no
banana,yellow,yes
mango,green-yellow-red,yes

bad,format
";
    // Read CSV data as StringRecord - disregard errors
    let mut rdr = csv::Reader::from_reader(csv_text.as_bytes());
    for record in rdr.records().flatten() {
        println!("{:?}", record);
    }
    println!();

    // Read CSV data as StringRecord - report errors
    let mut rdr = csv::Reader::from_reader(csv_text.as_bytes());
    for result in rdr.records() {
        if let Ok(record) = result {
            println!("{:?}", record);
        } else {
            println!("Error parsing csv");
        }
    }
    println!();

    // Read CSV data as StringRecord - report errors with details
    let mut rdr = csv::Reader::from_reader(csv_text.as_bytes());
    for result in rdr.records() {
        match result {
            Ok(record) => println!("{:?}", record),
            Err(err) => println!("Error parsing csv {err}"),
        }
    }
    println!();

    // Read CSV data as Struct - disregard errors
    let mut rdr = csv::Reader::from_reader(csv_text.as_bytes());
    for fruit in rdr.deserialize::<Fruit>().flatten() {
        println!("{fruit:?}");
    }
}

examples/csv/parse-csv-string/Cargo.toml
[package]
name = "parse-csv-string"
version = "0.1.0"
edition = "2021"

[dependencies]
csv = "1.3.0"
serde = { version = "1.0.213", features = ["derive"] }

StringRecord(["apple", "red", "no"])
StringRecord(["banana", "yellow", "yes"])
StringRecord(["mango", "green-yellow-red", "yes"])

StringRecord(["apple", "red", "no"])
StringRecord(["banana", "yellow", "yes"])
StringRecord(["mango", "green-yellow-red", "yes"])
Error parsing csv

StringRecord(["apple", "red", "no"])
StringRecord(["banana", "yellow", "yes"])
StringRecord(["mango", "green-yellow-red", "yes"])
Error parsing csv CSV error: record 4 (line: 6, byte: 76): found record with 2 fields, but the previous record has 3 fields

Fruit { fruit: "apple", color: "red", peal: "no" }
Fruit { fruit: "banana", color: "yellow", peal: "yes" }
Fruit { fruit: "mango", color: "green-yellow-red", peal: "yes" }