#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

#45 in #derive-deserialize

Download history 11/week @ 2023-11-27 1/week @ 2023-12-04 11/week @ 2023-12-11 12/week @ 2023-12-18 9/week @ 2023-12-25 22/week @ 2024-01-08 8/week @ 2024-01-15 6/week @ 2024-01-22 7/week @ 2024-01-29 9/week @ 2024-02-05 19/week @ 2024-02-12 33/week @ 2024-02-19 30/week @ 2024-02-26 30/week @ 2024-03-04 16/week @ 2024-03-11

112 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–3MB
~62K SLoC