find the size of a json file in rust

To find the size of a JSON file in Rust, we can use the standard library std::fs to read the file and get its metadata. We can use the serde library to deserialize the JSON file into a data structure. Here is an example function that takes a filename as input and returns the size of the file in bytes:

main.rs
use std::fs::metadata;
use std::io::{BufReader, Read, Result};
use serde_json::{Result as JsonResult, Value};

fn get_json_file_size(filename: &str) -> Result<u64> {
    let file = std::fs::File::open(filename)?;
    let metadata = metadata(filename)?;
    let mut buf_reader = BufReader::new(file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;
    let json: JsonResult<Value> = serde_json::from_str(&contents)?;
    Ok(metadata.len())
}
478 chars
14 lines

Here, we first open the file, get its metadata in order to retrieve the size of the file, and then read the contents of our JSON file into a string. Next, we use serde_json to deserialize the JSON into a JSON value. Finally, we return the size of the file in bytes.

Note that we're also handling potential errors by using the Result type to return the result of our function.

gistlibby LogSnag