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