This article uses JSON files as examples to demonstrate how to read and save JSON files in Rust using serde.

To implement JSON file reading and saving, we primarily use the following two functions:

  • serde_json::from_reader - reads and parses data from objects implementing the io::Read trait;
  • serde_json::to_writer - serializes the given data structure into JSON format and writes to objects implementing the io::Write trait;

Reference:

Reading from File

Save the following JSON data as config.json:

{
    "ip": "127.0.0.1",
    "port": 80
}

Read data from config.json and deserialize it:

use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::BufReader;

#[derive(Deserialize, Serialize)]
struct Config {
    ip: String,
    port: u16,
}

fn main() {

    let file = File::open("config.json").unwrap();

    let reader = BufReader::new(file);

    let config: Config = serde_json::from_reader(reader).unwrap();

    println!("{}:{}", config.ip,config.port);

}

Saving to File

Serialize data structure to JSON and write to file:

use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::BufWriter;

#[derive(Deserialize, Serialize)]
struct Config {
    ip: String,
    port: u16,
}

fn main() {

    let config = Config {
        ip : String::from("127.0.0.1"),
        port : 80,
    };

    let file = File::create("saved.json").unwrap();
    let writer = BufWriter::new(file);

    serde_json::to_writer(writer, &config).unwrap();
}