#serde-derive #file #serde #derive #yaml #derive-deserialize #read-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

#52 in #derive-deserialize

Download history 19/week @ 2024-04-07 22/week @ 2024-04-14 24/week @ 2024-04-21 22/week @ 2024-04-28 23/week @ 2024-05-05 22/week @ 2024-05-12 27/week @ 2024-05-19 167/week @ 2024-05-26 181/week @ 2024-06-02 179/week @ 2024-06-09 151/week @ 2024-06-16 181/week @ 2024-06-23 64/week @ 2024-06-30 24/week @ 2024-07-14 26/week @ 2024-07-21

118 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)

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