Rust: Convert a data structure into a JSON string

Mar 24, 2022

We've already done most of the heavy-lifting for turning a structure into JSON:

use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Serialize, Deserialize)]
struct Person {
    first_name: String,
    last_name: String,
    age: u8,
}

fn main() {
    let first_name = String::from("Glenn");
    let last_name = String::from("Gillen");
    let age = 40;
    let p = Person{ first_name, last_name, age };
    let data = serde_json::to_string(&p).expect("Not a serializable type");
    println!("{}", data)
}

Instantiate an instance of our Person, parse it into the serde via calling to_string. Done.

Hi, I'm Glenn! 👋 I'm currently Director of Product (Terraform) @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.