Skip to main content

json_to_csv

Function json_to_csv 

Source
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 CSV header row is the union of all keys across all objects, in the order they first appear; if a key is missing in a given object, the corresponding 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, and null becomes an empty cell. Nested objects and arrays cannot be represented losslessly in flat CSV and cause an error, ensuring round-trips never silently corrupt data.

§Errors

Returns an error if the JSON is not a valid array of objects, if any value is a nested object or array, 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");

Extra keys in later objects are preserved:

use sheeter_engine::json_to_csv;

let json = r#"[{"a":1},{"a":2,"b":3}]"#;
assert_eq!(json_to_csv(json).unwrap(), "a,b\n1,\n2,3\n");

Nested values are rejected:

use sheeter_engine::json_to_csv;

assert!(json_to_csv(r#"[{"a":{"nested":true}}]"#).is_err());