pub fn json_to_csv(json: &str) -> Result<String, Box<dyn Error>>Expand description
Converts a JSON array of objects into a CSV string.
JSON arrays of objects are a common way to represent tabular data. This function takes such a JSON string and produces a CSV string. The keys of the first object are used as the CSV header row. All objects are expected to have the same keys; if a key is missing in an object, the corresponding CSV cell is left empty. Values are converted to their string representation: strings are written as-is (without quotes), numbers and booleans use their JSON literal forms.
§Errors
Returns an error if the JSON is not a valid array of objects, or if CSV writing fails (e.g., due to I/O errors on the internal buffer).
§Examples
Basic conversion:
use sheeter_engine::json_to_csv;
let json = r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#;
let csv = json_to_csv(json).unwrap();
assert_eq!(csv, "name,age\nAlice,30\nBob,25\n");With numbers and booleans:
use sheeter_engine::json_to_csv;
let json = r#"[{"id":1,"active":true},{"id":2,"active":false}]"#;
let csv = json_to_csv(json).unwrap();
assert_eq!(csv, "id,active\n1,true\n2,false\n");