feagi_structures/feagi_json.rs
1use crate::FeagiDataError;
2
3/// A wrapper around serde_json::Value for handling JSON data in FEAGI.
4///
5/// Provides methods to create, parse, and manipulate JSON data with error handling.
6#[derive(Clone, Debug, Hash)]
7pub struct FeagiJSON {
8 json: serde_json::Value,
9}
10
11impl FeagiJSON {
12 /// Creates an empty JSON object.
13 ///
14 /// # Example
15 /// ```
16 /// use feagi_structures::FeagiJSON;
17 ///
18 /// let json = FeagiJSON::new_empty();
19 /// println!("{}", json); // prints: {}
20 /// ```
21 pub fn new_empty() -> FeagiJSON {
22 FeagiJSON {
23 json: serde_json::json!({}),
24 }
25 }
26
27 /// Parses a JSON string into a FeagiJSON wrapper.
28 ///
29 /// # Example
30 /// ```
31 /// use feagi_structures::FeagiJSON;
32 ///
33 /// let json = FeagiJSON::from_json_string(r#"{"key": "value"}"#.to_string()).unwrap();
34 /// ```
35 pub fn from_json_string(string: String) -> Result<FeagiJSON, FeagiDataError> {
36 match serde_json::from_str(&string) {
37 Ok(json_value) => Ok(FeagiJSON { json: json_value }),
38 Err(e) => Err(FeagiDataError::BadParameters(format!(
39 "Failed to parse JSON string: {}",
40 e
41 ))),
42 }
43 }
44
45 /// Creates a FeagiJSON from an existing serde_json::Value.
46 pub fn from_json_value(value: serde_json::Value) -> FeagiJSON {
47 FeagiJSON { json: value }
48 }
49
50 /// Returns a reference to the internal JSON value.
51 pub fn borrow_json_value(&self) -> &serde_json::Value {
52 &self.json
53 }
54
55 /// Updates the internal JSON value.
56 pub fn update_json_value(&mut self, new_value: serde_json::Value) {
57 self.json = new_value;
58 }
59}
60
61impl std::fmt::Display for FeagiJSON {
62 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
63 write!(f, "{}", self.json)
64 }
65}