Serde: flatten, but also prepend field name

Hi everyone, I want to flatten, because I don't want the JSON syntax of a nested object. but I do want it to prepend the field name. e.g.

use serde::*;
use serde_json::*;

#[derive(Serialize)]
struct Bar {
    a: &'static str,
    b: &'static str,
}

#[derive(Serialize)]
struct Baz {
    c: &'static str,
    d: &'static str,
}

#[derive(Serialize)]
struct Foo {
    #[serde(flatten)]
    bar: Bar,
    #[serde(flatten)]
    baz: Baz,
}

fn main() {
    let foo = Foo {
        bar: Bar {
            a: "a",
            b: "b",
        },
        baz: Baz {
            c: "c",
            d: "d",
        }
    };
    println!("{}", serde_json::to_string(&foo).unwrap());
}

Returns:

{"a":"a","b":"b","c":"c","d":"d"}

But I want:

{"bar_a":"a","bar_b":"b","baz_c":"c","baz_d":"d"}

Thanks!!

Thanks to the Rust Discord, looks like this is the answer: with_prefix in serde_with - Rust

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.