Parse CSV Records into Serde Structs
Deserialize CSV records into typed Serde structs with header mapping, numeric parsing, and an error on negative quantities.
Code
use serde::Deserialize;
use std::error::Error;
use std::io;
#[derive(Debug, Deserialize, PartialEq)]
struct InventoryRow {
sku: String,
quantity: u32,
price_cents: u32,
}
fn parse_inventory(csv_data: &str) -> Result<Vec<InventoryRow>, Box<dyn Error>> {
let mut reader = csv::ReaderBuilder::new()
.trim(csv::Trim::All)
.from_reader(io::Cursor::new(csv_data));
let mut rows = Vec::new();
for record in reader.deserialize() {
let row: InventoryRow = record?;
rows.push(row);
}
Ok(rows)
}
fn main() -> Result<(), Box<dyn Error>> {
let data = "sku,quantity,price_cents\nA-1,5,1200\nB-2,3,800\n";
let rows = parse_inventory(data)?;
println!("{} rows, first={:?}", rows.len(), rows.first());
assert_eq!(rows.len(), 2);
assert_eq!(
rows[0],
InventoryRow {
sku: "A-1".into(),
quantity: 5,
price_cents: 1200,
}
);
let bad = "sku,quantity,price_cents\nA-1,-5,1200\n";
assert!(parse_inventory(bad).is_err(), "negative quantity must fail");
Ok(())
}
How it works
Parse CSV Records into Serde Structs is built around the functions parse_inventory and main.
Repetition is confined to for record in reader.deserialize() — the rest of the file is straight-line. Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Caveats
- Dependency check:
serde::Deserialize— not built-in, must be present in the project. - Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Putting it to use
The primary signature is fn parse_inventory(csv_data: &str) -> Result<Vec<InventoryRow>, Box<dyn Error>>
main sequences parse_inventory; executing the file runs that flow once.
Core lines
fn parse_inventory(csv_data: &str) -> Result<Vec<InventoryRow>, Box<dyn Error>> {
let mut reader = csv::ReaderBuilder::new()
.trim(csv::Trim::All)
.from_reader(io::Cursor::new(csv_data));
let mut rows = Vec::new();
for record in reader.deserialize() {
let row: InventoryRow = record?;
rows.push(row);
}
Ok(rows)
}
let rows = parse_inventory(data)?;
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
FAQ
- Is there exception handling?
- As data, not exceptions: `Result` makes the caller handle both arms.
- Are there third-party dependencies?
- `serde::Deserialize` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.