How to Read and Write JSON Files in Rust

Use the serde_json crate with Serialize and Deserialize traits to convert between JSON strings and Rust structs.

Use the serde_json crate to parse JSON strings into Rust structs and serialize Rust structs back to JSON strings. Add serde and serde_json to your Cargo.toml, derive Serialize and Deserialize for your struct, then call serde_json::from_str to read and serde_json::to_string to write.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    age: u8,
}

fn main() {
    let json = r#"{"name":"Alice","age":30}"#;
    let user: User = serde_json::from_str(json).unwrap();
    let output = serde_json::to_string(&user).unwrap();
    println!("{}", output);
}