|
| 1 | +extern crate csv; |
| 2 | +extern crate serde_json; |
| 3 | + |
| 4 | +use std::io; |
| 5 | +use std::process; |
| 6 | +use serde_json::value::Value; |
| 7 | + |
| 8 | +pub fn json_to_csv(stdin: &str, csv_delimiter: u8) -> io::Result<()> { |
| 9 | + let mut is_array_of_objects = false; |
| 10 | + let mut wtr = csv::WriterBuilder::new() |
| 11 | + .delimiter(csv_delimiter) |
| 12 | + .from_writer(io::stdout()); |
| 13 | + if let Ok(json) = serde_json::from_str::<Value>(stdin) { |
| 14 | + if let Some(entries) = json.as_array() { |
| 15 | + if let Some(example) = entries.first() { |
| 16 | + if let Some(example_object) = example.as_object() { |
| 17 | + let ks = example_object.keys(); |
| 18 | + // WRITE THE HEADER using example |
| 19 | + wtr.write_record(ks)?; |
| 20 | + wtr.flush()?; |
| 21 | + is_array_of_objects = true; |
| 22 | + } else { |
| 23 | + eprintln!("Expected a JSON array of objects. Got: {}", json); |
| 24 | + process::exit(1); |
| 25 | + } |
| 26 | + } else { |
| 27 | + eprintln!("Will not write empty CSV, got empty JSON array."); |
| 28 | + process::exit(1); |
| 29 | + } |
| 30 | + |
| 31 | + // RECORDS |
| 32 | + if is_array_of_objects { |
| 33 | + for entry in entries { |
| 34 | + let o = entry.as_object().unwrap(); |
| 35 | + let vals = o.values().map(|x: &Value| match *x { |
| 36 | + Value::Null => "null".to_owned(), |
| 37 | + Value::Bool(ref b) => format!("{}", b), |
| 38 | + Value::Number(ref n) => format!("{}", n), |
| 39 | + Value::String(ref s) => s.to_owned(), |
| 40 | + Value::Array(ref a) => { |
| 41 | + eprintln!("Nested arrays not supported. Found {:?}", a); |
| 42 | + process::exit(1); |
| 43 | + } |
| 44 | + Value::Object(ref o) => { |
| 45 | + eprintln!("Nested objects not supported. Found {:?}", o); |
| 46 | + process::exit(1); |
| 47 | + } |
| 48 | + }); |
| 49 | + wtr.write_record(vals)?; |
| 50 | + } |
| 51 | + } |
| 52 | + } else { |
| 53 | + eprintln!("Expected a JSON array of objects. Got: {}", json); |
| 54 | + process::exit(1); |
| 55 | + } |
| 56 | + } else { |
| 57 | + eprintln!("Non-JSON found: {}", stdin); |
| 58 | + process::exit(1); |
| 59 | + } |
| 60 | + Ok(()) |
| 61 | +} |
| 62 | + |
| 63 | +#[cfg(test)] |
| 64 | +mod tests { |
| 65 | + #[test] |
| 66 | + fn it_works() {} |
| 67 | +} |
0 commit comments