Implement the Rust Display Trait to Render Structs as JSON

Sometimes we just want a simple technique to list the values of an object for logging, diagnostic, debugging, or other purposes. Serializing to JSON with the Display trait may not be comprehensive or consider all cases (for example, some values may require greater security), but could be one of the easiest possible approaches for developers learning rust, and can certainly be useful during coding and debugging.

To use serde to serialize structs to JSON, we can add something like this to the [dependencies] section in cargo.toml.

[dependencies]
derive-new = "0.5"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

The following a struct implements the Display trait to render itself as JSON.

#[derive(serde::Serialize)]
pub struct WinkConfig {
    cmd_name: String,
    verbose: bool,
    dry_run: bool,
    command_code: String,
    export: bool,
    pretty_print: bool,
    all_args: Vec<String>,
    cmd_args: Vec<String>,
    help_msg: String,
}

impl std::fmt::Display for WinkConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.pretty_print {
            write!(f, "{}", serde_json::to_string_pretty(&self).unwrap())
        } else {
            write!(f, "{}", serde_json::to_string(&self).unwrap())
        }
    }
}

There is probably a way to implement the function more generically, but WinkConfig just happens to support a pretty_print parameter used for controlling serialization of something else.

The following code uses a different function (Simple Case and Solution for Borrowing a Moved Value in Rust – rustapopoulos.com) to create an instance of the struct and render its values using that Display trait.

let config = wink::WinkConfig::get_from_cmd_line_args();
println!("Config: {0}", config);

What follows is part of the output of invoking the command (wink -epdv word a b c).

Config: {
  "cmd_name": "/home/jw/bin/wink",
  "verbose": true,
  "dry_run": true,
  "command_code": "word",
  "export": true,
  "pretty_print": true,
  "all_args": [
    "wink",
    "-epdv",
    "word",
    "a",
    "b",
    "c"
  ],
  "cmd_args": [
    "a",
    "b",
    "c"
  ],
  "help_msg": ""
}
//TODO: cmd_name should not include path

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: