jeudi 5 novembre 2015

Read json file in and write without indentation

The following code take a folder of json files (saved with indentation) open it, get content and serialize to json and write to file a new file. Same code task in python works, so it is not the data. But the rust version you see in here:

extern crate rustc_serialize;
use rustc_serialize::json;
use std::io::Read;
use std::fs::read_dir;
use std::fs::File;
use std::io::Write;
use std::io;
use std::str;


fn write_data(filepath: &str, data: json::Json) -> io::Result<()> {

    let mut ofile = try!(File::create(filepath));
    let encoded: String = json::encode(&data).unwrap();
    try!(ofile.write(encoded.as_bytes()));
    Ok(())
}


fn main() {

    let root = "/Users/bling/github/data/".to_string();
    let folder_path = root + &"texts";
    let paths = read_dir(folder_path).unwrap();

    for path in paths {
        let input_filename = format!("{}", path.unwrap().path().display());
        let output_filename = str::replace(&input_filename, "texts", "texts2");

        let mut data = String::new();
        let mut f = File::open(input_filename).unwrap();
        f.read_to_string(&mut data).unwrap();
        let json = json::Json::from_str(&data).unwrap();

        write_data(&output_filename, json).unwrap();
    }
}

Do you have spot an Error in my code already or did I get some language concepts wrong. Is the rustc-serialize cargo wrongly used. At the end it does not work as expected - to outperform python.

± % cargo run --release --verbose                                                                                                                                            
       Fresh rustc-serialize v0.3.16
       Fresh fileprocessing v0.1.0 (file:///Users/bling/github/rust/fileprocessing)
     Running `target/release/fileprocessing`
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: SyntaxError("unescaped control character in string", 759, 55)', ../src/libcore/result.rs:736
Process didn't exit successfully: `target/release/fileprocessing` (exit code: 101)

Aucun commentaire:

Enregistrer un commentaire