find the extension of a json file in rust

To find the extension of a JSON file in Rust, you can use the Path module from the standard library to extract the file extension. Here's an example:

main.rs
use std::path::Path;

fn main() {
    let file_path = Path::new("data.json");
    if let Some(extension) = file_path.extension() {
        if extension == "json" {
            println!("File extension is .{}", extension.to_string_lossy());
        } else {
            println!("File is not a JSON file");
        }
    } else {
        println!("File has no extension");
    }
}
380 chars
15 lines

In this example, we create a Path object for the file "data.json". We then use the extension() method to get the file extension, which returns an Option. If the file has an extension, we convert it to a string and check if it's equal to "json". If it is, we print the file extension. If not, we print a message saying the file is not a JSON file. If the file has no extension, we print a message saying so.

related categories

gistlibby LogSnag