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.
Duplicate header names are rejected because they would silently overwrite data in the resulting JSON objects. All cells are represented as strings in the JSON output; type information (numbers, booleans) is not inferred.
§Errors
Returns an error if the CSV is malformed (e.g., inconsistent number of columns), if a header name appears more than once, 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"}]"#);Duplicate headers are rejected:
use sheeter_engine::csv_to_json;
assert!(csv_to_json("a,a\n1,2").is_err());