Module json

Module json 

Source
Available on crate feature json only.
Expand description

With the json feature, this module provides the Json type.

This allows us to read and parse json files to some serde::Deserialize type, and write them back to disk.

§Examples

§Reading a json file

use std::path::Path;

use dir_structure::traits::sync::DirStructureItem;
use dir_structure::data_formats::json::Json;

#[derive(dir_structure::DirStructure)]
struct Dir {
    #[dir_structure(path = "f.json", with_newtype = Json<Obj>)]
    f: Obj,
}

#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Obj {
    name: String,
    age: u32,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let d = Path::new("dir");
    std::fs::create_dir_all(&d)?;
    std::fs::write(d.join("f.json"), r#"{"name":"John","age":30}"#)?;
    let dir = Dir::read(&d)?;
    assert_eq!(dir.f, Obj { name: "John".to_owned(), age: 30 });
    Ok(())
}

§Writing a json file

use std::path::Path;

use dir_structure::traits::sync::DirStructureItem;
use dir_structure::data_formats::json::Json;

#[derive(dir_structure::DirStructure)]
struct Dir {
    #[dir_structure(path = "f.json", with_newtype = Json<Obj>)]
    f: Obj,
}

#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Obj {
    name: String,
    age: u32,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let d = Path::new("dir");
    let dir = Dir {
        f: Obj {
            name: "John".to_owned(),
            age: 30,
        },
    };
    dir.write(&d)?;
    assert_eq!(std::fs::read_to_string(d.join("f.json"))?,
        r#"{"name":"John","age":30}"#
    );
    Ok(())
}

Structs§

Json
A wrapper around a type that implements serde::Serialize and serde::Deserialize, thus allowing us to parse and serialize it from / to json when we read / write a directory structure.
JsonRefWr
FromRefForWriter implementation for Json.