libjsonutils/
file.rs

1//! # Read & Write JSON Utilities
2//!
3//! A collection of utilities for reading and writing JSON files.
4//!
5use std::{fs::write, path::Path};
6
7use serde::{de::DeserializeOwned, Serialize};
8use serde_json::{from_value, ser::PrettyFormatter, Serializer};
9
10use crate::{
11    error::Error,
12    inner::{_create_parent_dir, _read_json_inner},
13};
14
15/// Reads a JSON file and deserializes it into a data structure.
16/// This function will error if the file cannot be read or deserialized into the aforementioned data structure.
17pub fn read_json<P: AsRef<Path>, T: DeserializeOwned>(path: P) -> Result<T, Error> {
18    let val = _read_json_inner(path)?;
19    from_value(val).map_err(Error::json)
20}
21
22/// Writes an object to a JSON file.
23/// This function will error if the file cannot be created or written to.
24pub fn write_json<T: Serialize, P: AsRef<Path>>(path: P, value: T) -> Result<(), Error> {
25    write_json_with_indent(path, value, 4)?;
26    Ok(())
27}
28
29/// Writes an object to a JSON file with a custom indentation.
30pub fn write_json_with_indent<T: Serialize, P: AsRef<Path>>(path: P, value: T, indent: usize) -> Result<(), Error> {
31    _create_parent_dir(&path)?;
32
33    let indent = " ".repeat(indent);
34    let indent = indent.as_bytes();
35
36    let mut buf = Vec::new();
37    let fmtr = PrettyFormatter::with_indent(indent);
38    let mut ser = Serializer::with_formatter(&mut buf, fmtr);
39
40    value.serialize(&mut ser).map_err(Error::json)?;
41    write(path, buf).map_err(Error::io)?;
42
43    Ok(())
44}