#serde #derive #file

from_file

A simple convenience to deserialize a rust Struct or Enum directly from a json or yaml file path

4 releases

Uses old Rust 2015

0.1.3 Dec 2, 2018
0.1.2 Nov 30, 2018
0.1.1 Nov 30, 2018
0.1.0 Nov 30, 2018

#2227 in Rust patterns

Download history 43/week @ 2023-01-23 51/week @ 2023-01-30 17/week @ 2023-02-06 44/week @ 2023-02-13 42/week @ 2023-02-20 21/week @ 2023-02-27 31/week @ 2023-03-06 20/week @ 2023-03-13 4/week @ 2023-03-20 14/week @ 2023-03-27 18/week @ 2023-04-03 28/week @ 2023-04-10 3/week @ 2023-04-17 20/week @ 2023-04-24 16/week @ 2023-05-01 16/week @ 2023-05-08

55 downloads per month
Used in 5 crates (4 directly)

MIT license

10KB
118 lines

This crate provides the trait [FromFile] that can be implemented or derived for any struct or enum. Upon doing so, you'll get a from_file method that allows you to skip having read the file the disk & choosing the correct serde method - that will be done based on the file extension.

Quick Preview

All examples require that serde Deserialize is also derived. (see below for copy/paste example)

# #[macro_use]
# extern crate serde_derive;
# extern crate serde;
# #[macro_use]
# extern crate from_file_derive;
# use from_file::FromFile;
#[derive(Deserialize)]
struct Person {
    name: String
}

impl FromFile for Person {}

fn main() {
    let path = "test/fixtures/person.json";
    let person = Person::from_file(path).expect("deserialize from file");
    assert_eq!(person.name, String::from("Shane"));
}

Quick Preview with from_file_derive

This requires the additional crate from_file_derive

# #[macro_use]
# extern crate serde_derive;
# extern crate serde;
# #[macro_use]
# extern crate from_file_derive;
# use from_file::FromFile;
#[derive(Deserialize, FromFile)]
struct Person {
    name: String
}

fn main() {
    let path = "test/fixtures/person.json";
    let person = Person::from_file(path).expect("deserialize from file");
    assert_eq!(person.name, String::from("Shane"));
}

Copy/Paste example

#[macro_use]
extern crate serde_derive;
extern crate serde;

#[macro_use]
extern crate from_file_derive;

use from_file::FromFile;

#[derive(Deserialize, FromFile)]
struct Person {
    name: String
}

fn main() {
    let path = "test/fixtures/person.json";
    let person = Person::from_file(path).expect("deserialize from file");
    assert_eq!(person.name, String::from("Shane"));
}

Full example with imports and error handing

#[macro_use]
extern crate serde_derive;

#[macro_use]
extern crate from_file_derive;
extern crate from_file;

use from_file::FromFile;

#[derive(Deserialize, FromFile, Debug, PartialEq)]
struct Person {
    name: String,
    age: usize
}

fn main() {
    match Person::from_file("test/fixtures/person.json") {
        Ok(p) => println!("Got a Person from a file!"),
        Err(e) => eprintln!("{}", e)
    }
}

Dependencies

~1.7–2.6MB
~60K SLoC