stac_io/
json.rs

1use crate::Result;
2use serde::Serialize;
3use stac::{FromJson, SelfHref, ToJson};
4use std::{fs::File, io::Read, path::Path};
5
6/// Create a STAC object from JSON.
7pub trait FromJsonPath: FromJson + SelfHref {
8    /// Reads JSON data from a file.
9    ///
10    /// # Examples
11    ///
12    /// ```
13    /// use stac::Item;
14    /// use stac_io::FromJsonPath;
15    ///
16    /// let item = Item::from_json_path("examples/simple-item.json").unwrap();
17    /// ```
18    fn from_json_path(path: impl AsRef<Path>) -> Result<Self> {
19        let path = path.as_ref();
20        let mut buf = Vec::new();
21        let _ = File::open(path)?.read_to_end(&mut buf)?;
22        let mut value = Self::from_json_slice(&buf)?;
23        value.set_self_href(path.to_string_lossy());
24        Ok(value)
25    }
26}
27
28pub trait ToJsonPath: ToJson {
29    /// Writes a value to a path as JSON.
30    ///
31    /// # Examples
32    ///
33    /// ```no_run
34    /// use stac::Item;
35    /// use stac_io::ToJsonPath;
36    ///
37    /// Item::new("an-id").to_json_path("an-id.json", true).unwrap();
38    /// ```
39    fn to_json_path(&self, path: impl AsRef<Path>, pretty: bool) -> Result<()> {
40        let file = File::create(path)?;
41        self.to_json_writer(file, pretty)?;
42        Ok(())
43    }
44}
45
46impl<T: FromJson + SelfHref> FromJsonPath for T {}
47impl<T: Serialize> ToJsonPath for T {}
48
49#[cfg(test)]
50mod tests {
51    use super::FromJsonPath;
52    use stac::{Item, SelfHref};
53
54    #[test]
55    fn set_href() {
56        let item = Item::from_json_path("examples/simple-item.json").unwrap();
57        assert!(
58            item.self_href()
59                .unwrap()
60                .ends_with("examples/simple-item.json")
61        );
62    }
63}