copy a json file in rust

To copy a JSON file in Rust, you can make use of the serde crate to deserialize the JSON file into a struct, and then serialize it into another file using the fs and io modules.

Here's an example code snippet:

main.rs
use std::fs::{File};
use std::io::{Read, Write};
use serde::{Deserialize, Serialize};

// Define a struct that matches the keys/values of your JSON
#[derive(Debug, Deserialize, Serialize)]
struct MyData {
    key1: String,
    key2: i32,
    key3: bool,
}

fn main() -> std::io::Result<()> {
    // Open the source JSON file
    let mut file = File::open("source.json")?;

    // Read the contents of the file into a string
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    // Deserialize the JSON into a struct
    let original_data: MyData = serde_json::from_str(&contents)?;

    // Serialize the struct into a new file
    let mut new_file = File::create("new.json")?;
    let serialized = serde_json::to_string(&original_data)?;
    new_file.write_all(serialized.as_bytes())?;

    Ok(())
}
830 chars
31 lines

This will read the contents of the source.json file into a string, deserialize it into a MyData struct using serde_json::from_str, and then serialize it into a new file named new.json using serde_json::to_string and new_file.write_all.

Note that you will need to have the serde and serde_json crates in your Cargo.toml file in order for this to work:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
85 chars
4 lines

related categories

gistlibby LogSnag