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

Prefix name of flattened fields #2071

Closed
t-cadet opened this issue Aug 10, 2021 · 2 comments
Closed

Prefix name of flattened fields #2071

t-cadet opened this issue Aug 10, 2021 · 2 comments

Comments

@t-cadet
Copy link

t-cadet commented Aug 10, 2021

Usecase

I want to serialize a struct containing other structs to CSV, which is why I use flatten.
However some of these structs have fields with the same name, which make the output unpractical to read.
I would like to prefix the flattened fields to be able to distinguish them.

Minimal example

use serde::Serialize;

fn main() {
    let json = serde_json::to_string(&Message::default()).unwrap();
    println!("{}", json);
}

#[derive(Serialize, Default)]
struct Message {
    content: String,
    #[serde(flatten)] // put new feature here
    from: Person,
    #[serde(flatten)] // put new feature here
    to: Person,
}

#[derive(Serialize, Default)]
struct Person {
    name: String,
}

Output

{"content":"","name":"","name":""}

Wanted Output example

{"content":"","from.name":"","to.name":""}

Maybe this could be implemented as an option on the flatten macro, or as an extension on the renaming macro ?

@jonasbb
Copy link
Contributor

jonasbb commented Aug 10, 2021

This is very similar to the request in #970. The suggested solution is to use the serde_with::with_prefix! macro.

serde_with::with_prefix!(prefix_from "from.");
serde_with::with_prefix!(prefix_to "to.");

#[derive(Serialize, Default)]
struct Message {
    content: String,
    #[serde(flatten, with = "prefix_from")]
    from: Person,
    #[serde(flatten, with = "prefix_to")]
    to: Person,
}

However, IIRC, the csv crate does not support structs which use flatten internally.

@dtolnay
Copy link
Member

dtolnay commented Jan 23, 2022

I'd prefer not to build anything for this into this crate, so for now the suggestion is to use serde_with's macro for this.

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

No branches or pull requests

3 participants