Read CSV file into hashes



examples/csv/csv-hash/planets.csv
Planet name,Distance (AU),Mass
Mercury,0.4,0.055
Venus,0.7,0.815
Earth,1,1
Mars,1.5,0.107
Ceres,2.77,0.00015
Jupiter,5.2,318
Saturn,9.5,95
Uranus,19.6,14
Neptune,30,17
Pluto,39,0.00218
Charon,39,0.000254


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

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
csv = "1.2.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.97"

examples/csv/csv-hash/src/main.rs
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;

type Record = HashMap<String, String>;

fn main() {
    let filepath = "planets.csv";
    let result = read_file(filepath);
    match result {
        Ok(rows) => {
            for row in &rows {
                println!("{:?}", row);
                println!("{}", row["Planet name"]);
            }
            println!("---");
            println!("{}", rows[3]["Planet name"]);
        }
        Err(err) => panic!("Error: {}", err),
    }
}

fn read_file(filepath: &str) -> Result<Vec<Record>, Box<dyn Error>> {
    let mut records: Vec<Record> = vec![];
    match File::open(filepath) {
        Ok(file) => {
            let mut rdr = csv::Reader::from_reader(file);
            for result in rdr.deserialize() {
                let record: Record = result?;
                records.push(record);
            }
        }
        Err(error) => panic!("Error opening file {}: {}", filepath, error),
    }
    Ok(records)
}

{"Mass": "0.055", "Planet name": "Mercury", "Distance (AU)": "0.4"}
Mercury
{"Distance (AU)": "0.7", "Planet name": "Venus", "Mass": "0.815"}
Venus
{"Planet name": "Earth", "Distance (AU)": "1", "Mass": "1"}
Earth
{"Mass": "0.107", "Distance (AU)": "1.5", "Planet name": "Mars"}
Mars
{"Planet name": "Ceres", "Distance (AU)": "2.77", "Mass": "0.00015"}
Ceres
{"Distance (AU)": "5.2", "Mass": "318", "Planet name": "Jupiter"}
Jupiter
{"Distance (AU)": "9.5", "Planet name": "Saturn", "Mass": "95"}
Saturn
{"Planet name": "Uranus", "Mass": "14", "Distance (AU)": "19.6"}
Uranus
{"Planet name": "Neptune", "Mass": "17", "Distance (AU)": "30"}
Neptune
{"Distance (AU)": "39", "Mass": "0.00218", "Planet name": "Pluto"}
Pluto
{"Planet name": "Charon", "Mass": "0.000254", "Distance (AU)": "39"}
Charon
---
Mars