home ~ projects ~ socials

Serialize a Rust Struct into a JSON String with serde_json

Make It JSON

This is how I'm converting Rust structs into JSON strings:

---
[dependencies]
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
---

use serde::Serialize;

#[derive(Serialize)]
pub struct Widget{
  alfa: String,
  bravo: Vec<String>
}

fn main() {
  let widget = Widget{
    alfa: "the quick brown fox".to_string(),
    bravo: vec![
      "jumps over".to_string(),
      "the lazy dog".to_string()
    ]
  };

  if let Ok(json) = 
    serde_json::to_string_pretty(&widget) {
    println!("{}", json);
  } else {
    println!("Could not serizlize to json");
  }
}
Output:
{
  "alfa": "the quick brown fox",
  "bravo": [
    "jumps over",
    "the lazy dog"
  ]
}

Notes

  • I'm using serde_json::to_string_pretty() for the example to pretty print it.
  • There is also serde_json::to_string() if you don't need the nice formatting (e.g. if you're using it for data instead of display)

Nice and straight forward. Gotta love it.

-a

-- end of line --

References