structured_output/
lib.rs

1//! A library for creating structured output for command line applications.
2//!
3//!
4//! # Example
5//!
6//! ```
7//! use structured_output::StructuredOutput;
8//!
9//! let lines = "Hello world!";
10//! let json = serde_json::json!({ "message": lines });
11//! let output = StructuredOutput::new(lines, json.clone());
12//! assert_eq!(output.lines(), "Hello world!");
13//! assert_eq!(output.json(), &json);
14//! ```
15//!
16
17#[derive(Debug, Default, Clone, PartialEq)]
18/// A struct that contains both a string and a json value.
19pub struct StructuredOutput {
20    pub lines: String,
21    pub json: serde_json::Value,
22}
23
24impl StructuredOutput {
25    /// Create a new [StructuredOutput] that includes both a string and a json value.
26    ///
27    pub fn new(lines: impl Into<String>, json: impl Into<serde_json::Value>) -> StructuredOutput {
28        StructuredOutput {
29            lines: lines.into(),
30            json: json.into(),
31        }
32    }
33
34    /// Get the string value of the output.
35    ///
36    pub fn lines(&self) -> &str {
37        &self.lines
38    }
39
40    /// Get the json value of the output.
41    pub fn json(&self) -> &serde_json::Value {
42        &self.json
43    }
44
45    /// Get the json value of the output as a JSON string.
46    pub fn to_json_string(&self) -> String {
47        serde_json::to_string(&self.json).unwrap()
48    }
49
50    /// Get the json value of the output as a prettified JSON string.
51    pub fn to_json_pretty(&self) -> String {
52        serde_json::to_string_pretty(&self.json).unwrap()
53    }
54}
55
56impl std::fmt::Display for StructuredOutput {
57    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
58        write!(f, "{}", self.lines)
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn it_works() {
68        let lines = "Hello world!";
69        let json = serde_json::json!({ "message": lines });
70        let output = StructuredOutput::new(lines, json.clone());
71        assert_eq!(output.lines(), "Hello world!");
72        assert_eq!(output.json(), &json);
73    }
74}