rustHow to convert struct to JSON string in Rust?
Converting a struct to a JSON string in Rust can be done using the serde crate. serde provides a set of macros to serialize and deserialize data structures to and from JSON.
Example code
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}
fn main() {
    let person = Person {
        name: "John".to_string(),
        age: 30,
    };
    let json_string = serde_json::to_string(&person).unwrap();
    println!("{}", json_string);
}
Output example
{"name":"John","age":30}
Code explanation
use serde::{Serialize, Deserialize};: imports theSerializeandDeserializetraits from theserdecrate.#[derive(Serialize, Deserialize)]: derives theSerializeandDeserializetraits for thePersonstruct.serde_json::to_string(&person).unwrap(): serializes thepersonstruct to a JSON string.
Helpful links
Related
More of Rust
- How to use non-capturing groups in Rust regex?
 - Regex example to match multiline string in Rust?
 - How to replace a capture group using Rust regex?
 - How to match the end of a line in a Rust regex?
 - How to use backslash in regex in Rust?
 - How to use binary regex in Rust?
 - Hashshet example in Rust
 - How to add a value to a Rust HashMap?
 - How to add an entry to a Rust HashMap?
 - How to convert a Rust slice of u8 to u32?
 
See more codes...