Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about (de)serializing vectors #254

Closed
corvusrabus opened this issue Nov 25, 2021 · 4 comments
Closed

Question about (de)serializing vectors #254

corvusrabus opened this issue Nov 25, 2021 · 4 comments

Comments

@corvusrabus
Copy link

corvusrabus commented Nov 25, 2021

Hi, thanks for providing this great crate.
Currently, when I am using the crate to serialise a vector inside a struct it will be flattened, so say I have:

struct A {
a : String,
b : Vec<i64>
}

and I have a flexible writer, then two As {"Hello",[1,2,3]}, {"Bye", [4,5,6,7]} would be serialized to
"Hello", 1,2,3,
"Bye", 4,5,6,7

Is there any way I can tell the CSV writer to serialize it to
"Hello", [1,2,3]
"Bye", [4,5,6,7]
?

@BurntSushi
Copy link
Owner

Please provide a complete Rust program, any relevant inputs, actual output and desired output.

@corvusrabus
Copy link
Author

Program

use std::io;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct A {
a: String,
b: Vec,
}

fn main() {
let x = A { a: "Hello".to_string(), b: vec![1, 2, 3] };
let y = A { a: "Bye".to_string(), b: vec![4, 5, 6, 7] };
let mut w = csv::WriterBuilder::new()
.flexible(true).has_headers(false).from_writer(io::stdout());
w.serialize(x);
w.serialize(y);
}

Actual output
Hello,1,2,3
Bye,4,5,6,7
Desired output
Hello,[1,2,3]
Bye,[4,5,6,7]

@ammernico
Copy link

Hi, I have the same problem. But I guess the behavior is known since it's documented here:
Nested containers are flattened to their scalar components
https://docs.rs/csv/1.3.0/csv/struct.Writer.html#non-struct-containers

Is this behavior desired? It seems an odd choice for serializing into csv

@BurntSushi
Copy link
Owner

BurntSushi commented Nov 22, 2023

It's not only desired, I'm not aware of any reasonable alternative other than disallowing it entirely. If you call it odd, why not say why it's odd and suggest an alternative behavior?

The OP's suggestion is not reasonable here because it layers a completely different serialization format that is not CSV on top of CSV.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants