file read, json parse
This commit is contained in:
		
							
								
								
									
										45
									
								
								src/main.rs
									
									
									
									
									
								
							
							
						
						
									
										45
									
								
								src/main.rs
									
									
									
									
									
								
							@@ -1,3 +1,46 @@
 | 
			
		||||
use std::collections::HashMap;
 | 
			
		||||
use std::fs::File;
 | 
			
		||||
use std::io::{ErrorKind, Read};
 | 
			
		||||
use std::path::Path;
 | 
			
		||||
use std::process::exit;
 | 
			
		||||
 | 
			
		||||
fn main() {
 | 
			
		||||
    println!("Hello, world!");
 | 
			
		||||
    let data_file = Path::new("data.json");
 | 
			
		||||
    get_json(data_file);
 | 
			
		||||
    
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
fn get_json(path: &Path) -> HashMap<String, String> {
 | 
			
		||||
    let mut data = HashMap::new();
 | 
			
		||||
    let json_data = read_file(path);
 | 
			
		||||
    
 | 
			
		||||
    // fixme
 | 
			
		||||
    let parsed_data = json::parse(json_data.as_str()).unwrap();
 | 
			
		||||
    println!("{}", parsed_data);
 | 
			
		||||
    
 | 
			
		||||
    data
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
fn read_file(path: &Path) -> String {
 | 
			
		||||
    let read_result = File::open(path);
 | 
			
		||||
    let mut result= String::new();
 | 
			
		||||
    
 | 
			
		||||
    match read_result {
 | 
			
		||||
        Ok(mut t) => {
 | 
			
		||||
            // file exists
 | 
			
		||||
            println!("[INFO] JSON file located, reading ...");
 | 
			
		||||
            match t.read_to_string(&mut result) { 
 | 
			
		||||
                // handling the reading
 | 
			
		||||
                Ok(_r) => result,
 | 
			
		||||
                Err(e) => panic!("[ERROR] While reading the file: {e}"),
 | 
			
		||||
            }
 | 
			
		||||
        },
 | 
			
		||||
        Err(err) => match err.kind() {
 | 
			
		||||
            ErrorKind::NotFound => {
 | 
			
		||||
                println!("[ERROR] {} does not exist", path.display());
 | 
			
		||||
                exit(1);
 | 
			
		||||
            },
 | 
			
		||||
            _ => panic!("[ERROR] Unexpected error, closing ..."),
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user