#serde-derive #file #serde #derive #derive-deserialize #read-file #file-extension

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

#39 in #derive-deserialize


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)

#[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

#[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

~2.1–3MB
~65K SLoC