FAQ - Help and questions

How do I load and save app settings as a JSON file with serde?

#settings#serde#json#desktoppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Derive Serialize and Deserialize on a settings struct with a Default, load it with unwrap_or_default so a missing or unreadable file means defaults, create the folder before writing, and save with serde_json::to_string_pretty. The full program was compiled and run on Windows and its output is shown.

Checked with rustc 1.93.0, Windows 11, serde 1.x and serde_json 1.x; compiled and run, using a temporary folder that the program deletes afterwards.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A settings file is a struct on disk. With serde you describe it once and get reading and writing for free. Three decisions make it robust: a Default for first runs, the folder created before the first save, and no panic when the file is missing or damaged.

Cargo.tomltoml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rsrust
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Settings {
    dark_mode: bool,
    font_size: u32,
    recent_files: Vec<String>,
}

impl Default for Settings {
    fn default() -> Self {
        Settings { dark_mode: false, font_size: 14, recent_files: Vec::new() }
    }
}

fn load(path: &Path) -> Settings {
    fs::read_to_string(path)
        .ok()
        .and_then(|text| serde_json::from_str(&text).ok())
        .unwrap_or_default() // missing or unreadable file: start with the defaults
}

fn save(path: &Path, s: &Settings) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir)?; // the app's folder does not exist on first run
    }
    let json = serde_json::to_string_pretty(s).expect("settings are always serializable");
    fs::write(path, json)
}

fn main() -> std::io::Result<()> {
    let path = std::env::temp_dir().join("rs-forum-settings-demo").join("settings.json");
    let mut s = load(&path);
    println!("first run: {s:?}");
    s.dark_mode = true;
    s.recent_files.push("report.txt".into());
    save(&path, &s)?;
    let again = load(&path);
    println!("second run: {again:?}");
    assert_eq!(s, again);
    println!("{}", fs::read_to_string(&path)?);
    fs::remove_dir_all(path.parent().unwrap())
}
text
first run: Settings { dark_mode: false, font_size: 14, recent_files: [] }
second run: Settings { dark_mode: true, font_size: 14, recent_files: ["report.txt"] }
{
  "dark_mode": true,
  "font_size": 14,
  "recent_files": [
    "report.txt"
  ]
}

In a real app, replace the temporary folder with your app's folder from the dirs crate (see the thread on where to store settings), save when the user changes something or when the app closes, and write atomically (see the thread on saving safely).

Common mistakes#

  • Treating .ok() as "no problem". Silently using defaults for a damaged file means the next save overwrites the user's real settings; see the thread on damaged settings files.
  • Adding a field to the struct and breaking old files. See the thread on settings versions.
  • Saving on every keystroke or slider move. Save when the change is finished.

JSON, TOML or something else?#

Any serde format works the same way. TOML reads well for files people edit by hand; JSON is the most widely understood. Choose by who edits the file.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet