Crate serde_loader

source ·
Expand description

Serde wrapper to load/save serializable data from relative paths. This crate provides special wrappers to ser/deserialize type from a file path. The following wrappers are provided:

It enables to read or write the file path instead of data during de/serialization. For example, we can have a main.json file that loads external.json.

main.json

{
    "external": "external.json"
}

The type type definition is defined as follows.

use serde_loader::JsonPath;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Main {
    pub external: JsonPath<External>
}

#[derive(Serialize, Deserialize)]
struct External {
    data: String
}

// open file
let main: JsonPath<Main> = JsonPath::open("main.json")?;

// access data
let data = &main.external.data;

Recursive File Loading

The file path is relative to the file where the field is defined. It tracks file paths automatically and allows recursive file loading.

Suppose we have the following files.

main.json

{
    "sub": "sub/sub.json"
}

sub/sub.json

{
    "sub": "sub/sub.json"
}

sub/sub/sub_of_sub.json

{
    "sub": "sub/sub_of_sub.json"
}

Let’s load the files recursively.

use serde_loader::JsonPath;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Main {
    pub sub: JsonPath<Sub>
}


#[derive(Serialize, Deserialize)]
struct Sub {
    pub sub: JsonPath<SubOfSub>
}


#[derive(Serialize, Deserialize)]
struct SubOfSub {
    pub name: String,
    pub value: String,
}

let config: JsonPath<Main> = JsonPath::open("tests/config-example/main.json")?;
config.save()?;

Re-exports

Modules

Type Definitions