pub fn csv_to_json(csv: &str) -> Result<String, Box<dyn Error>>Expand description
Converts a CSV string into a JSON array of objects.
CSV (Comma-Separated Values) is a simple tabular format where each line is a row and columns are separated by commas. JSON (JavaScript Object Notation) is a hierarchical data format. This function reads the first row of the CSV as the header (column names) and each subsequent row as a data record. It then builds a JSON array where each element is an object mapping header names to the corresponding cell values as strings. This is useful for feeding CSV data into JSON-based systems or APIs, or for further processing with JSON tools.
§Errors
Returns an error if the CSV is malformed (e.g., inconsistent number of columns) or if JSON serialization fails (which is unlikely for simple string maps).
§Examples
Basic conversion:
use sheeter_engine::csv_to_json;
let csv = "name,age\nAlice,30\nBob,25";
let json = csv_to_json(csv).unwrap();
assert_eq!(json, r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#);Single column:
use sheeter_engine::csv_to_json;
let csv = "id\n1\n2\n3";
let json = csv_to_json(csv).unwrap();
assert_eq!(json, r#"[{"id":"1"},{"id":"2"},{"id":"3"}]"#);