Home > Blockchain >  Json file serialization and deserialization
Json file serialization and deserialization

Time:01-23

I have a json file:

[
    {
        "name": "John",
        "sirname": "Fogerty",
        "age": 77
    },
    {
        "name": "Dave",
        "sirname": "Mustaine",
        "age": 61
    }
]

I want to read the objects of the User structure from it into an array, then add another element to this array and re-write everything to the same file.

My code:

use serde_derive::{Serialize, Deserialize};
use serde_json::json;
use std::fs::File;

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

fn main() {
    let f = File::open("info.json").unwrap();

    let mut q: Vec<User> = serde_json::from_reader(&f).unwrap();
    q.push(User{name: "Daniil".to_string(),
        sirname: "Volkov".to_string(),
        age: 19,
    });

    serde_json::to_writer(f, &q).unwrap();
    println!("{:?}", q);
    
}

I get an error when starting:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Error("Access denied. (os error 5)", line: 0, column: 0)', src\main.rs:22:34
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
error: process didn't exit successfully: target\debug\json.exe (exit code: 101).

What do I need to do?

CodePudding user response:

As noted by @Caesar in comments, you should change the way you open your file. Thus instead of

let f = File::open("info.json").unwrap();

you should put the following:

let mut f = File::options()
    .read(true)
    .write(true)
    .open("info.json")
    .unwrap();

But as you read your file your position in that file moves, so before writing to the file (since you are willing to rewrite it, not append) you need to reset the position:

let _ = f.seek(std::io::SeekFrom::Start(0)).unwrap();

right before the following line:

serde_json::to_writer(f, &q).unwrap();
  • Related