#Trying to create a .json file with serde-json (How to create a Map and write that).

9 messages · Page 1 of 1 (latest)

jaunty shoal
#

Hello, I am really new to Rust and I am trying to write and read a .json file with serde.
It works fine, but I want to "upgrade" from just a string to a Map (I think that's what I want), because the .json file looks like this:

{"title":"Color:","red":255,"green":100,"blue":100}

But I want to have it like a "real" .json file where I have color: and then the 3 values, but I've no idea how to create a Map and couldn't find anything online.
This is my current code (a snippet):

    println!("{}", "change options here".yellow());
    println!("Type in: xxx xxx xxx | RGB Code (Red Green Blue)");

    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Error");

    let v: Vec<&str> = input.split(' ').collect();

    let data = Color {
        title: String::from("Color:"),
        red: v[0].trim().parse().unwrap(),
        green: v[1].trim().parse().unwrap(),
        blue: v[2].trim().parse().unwrap(),
    };

    let serialized = serde_json::to_string(&data).unwrap();

    File::create("color.json")?;
    fs::write("color.json", serialized)?;

    println!(
        "This is your color: {}",
        "nice".truecolor(data.red, data.green, data.blue)
    );
misty saddle
#

you could just write the 3 values into the file directly however you want it, without using a custom struct

#

but if i understand correctly, you want it to serialize into this? ```json
{"color":[255,100,100]}

#

i guess one way is to do this:

#[derive(Clone, Serialize)]
#[serde(into = "ColorSerialized")]
struct Color {
    red: u8,
    green: u8,
    blue: u8,
}

#[derive(Serialize)]
struct ColorSerialized {
    color: [u8; 3],
}

impl From<Color> for ColorSerialized {
    fn from(c: Color) -> Self {
        Self {
            color: [c.red, c.green, c.blue],
        }
    }
}
jaunty shoal
clear terrace
misty saddle
#

But you’d probably need to impl From<ColorSerialized> for Color too