#creating json file w serde

24 messages · Page 1 of 1 (latest)

noble lantern
#
pub fn create_reserves_record(block: U64, log: (Vec<PairA>, U256)) {
    println!("  ~ Attempting to create json.");
    let j = serde_json::to_string(&log).expect("prettyify error");
    let new_dir = format!("./src/logs/{}.json", block); 
    match std::fs::create_dir(&new_dir) {
        Ok(_) => {
            std::fs::write(new_dir, j).expect("unable to write to json");
            println!("  ~ [PASS] Created JSON");
        },
        Err(_) => println!("  ~ [FAILED] Created JSON"),
    }
}

I think im just creating the same directory instead of a json .-.

meager kelp
#

Were you expecting a directory and a file with the same name to be allowed?

#

Because that's what you have there

noble lantern
#

how would i make a file then?

meager kelp
#

Presumably you wanted to do this

pub fn create_reserves_record(block: U64, log: (Vec<PairA>, U256)) {
    println!("  ~ Attempting to create json.");
    let j = serde_json::to_string(&log).expect("prettyify error");
    let new_dir = std::path::Path::new("./src/logs/");
    match std::fs::create_dir(new_dir) {
        Ok(_) => {
            let new_file = new_dir.join(format!("{block}.json")); 
            std::fs::write(new_file, j).expect("unable to write to json");
            println!("  ~ [PASS] Created JSON");
        },
        Err(_) => println!("  ~ [FAILED] Created JSON"),
    }
}

Create a ./src/logs/ directory, and a json file inside

noble lantern
#

they made files though

meager kelp
#

That looks like directories

#

they even have the folder icon

meager kelp
#

Yes, I have no doubt that it did.

#

Wait, did you delete those before running my version?

noble lantern
#

thats what ran when i put your code in

#

i replaced it again

meager kelp
#

You dragged the curson from pub to the last }, then copy pasted that?

noble lantern
#

and it fails at the match

meager kelp
#

Because the log folder already exists?

noble lantern
#

oh that might be it

#

let me try again

#

that worked

#

but i need to create a new file for each loop iteration in that folder

#

thats why i had the log folder already there

meager kelp
#

Well, if you want to create the directory only when necessary, then you'll need to ignore the AlreadyExists error:

pub fn create_reserves_record(block: U64, log: (Vec<PairA>, U256)) {
    println!("  ~ Attempting to create json.");
    let j = serde_json::to_string(&log).expect("prettyify error");
    let new_dir = std::path::Path::new("./src/logs/");
    match std::fs::create_dir(new_dir) {
        Err(e) if error.kind() != std::io::ErrorKind::AlreadyExists => {
            println!("  ~ [FAILED] Created JSON")
        }
        _ => {
            let new_file = new_dir.join(format!("{block}.json")); 
            std::fs::write(new_file, j).expect("unable to write to json");
            println!("  ~ [PASS] Created JSON");
        }
    }
}