home ~ projects ~ socials

Turn A CSV Into A Generic JSON Array Of Arrays In Rust

```cargo
[dependencies]
csv = "1.3.0"
serde = "1.0.214"
serde_json = "1.0.132"
```

use csv::ReaderBuilder;
use serde_json;
use serde_json::json;
use serde_json::Value;

fn main() {
  let source = "a,b,c\nd,e,f\ng,h,i";
  let data = parse_csv(source);
  dbg!(data);
}

fn parse_csv(source: &str) -> Value {
  let mut items: Vec<Vec<String>> = vec![];
  let mut rdr = ReaderBuilder::new()
      .has_headers(false)
      .delimiter(b',')
      .from_reader(source.as_bytes());
  for result in rdr.deserialize() {
    match result {
      Ok(record) => items.push(record),
      Err(_) => ()
    }
  }
  json!(items)
}
Output:
[/Users/alan/.cargo/target/55/19854259915251/_active_nvim_run:16:3] data = Array [
    Array [
        String("a"),
        String("b"),
        String("c"),
    ],
    Array [
        String("d"),
        String("e"),
        String("f"),
    ],
    Array [
        String("g"),
        String("h"),
        String("i"),
    ],
]
-- end of line --