diff --git a/src/built_in_functions/data_formats.rs b/src/built_in_functions/data_formats.rs new file mode 100644 index 0000000..e64c6e8 --- /dev/null +++ b/src/built_in_functions/data_formats.rs @@ -0,0 +1,35 @@ +use crate::{BuiltInFunction, Error, Map, Result, Value}; + +pub struct FromJson; + +impl BuiltInFunction for FromJson { + fn name(&self) -> &'static str { + "from_json" + } + + fn run(&self, arguments: &[Value], _context: &Map) -> Result { + Error::expect_built_in_function_argument_amount(self, 1, arguments.len())?; + + let json_string = arguments.first().unwrap().as_string()?; + let value = serde_json::from_str(&json_string)?; + + Ok(value) + } +} + +pub struct ToJson; + +impl BuiltInFunction for ToJson { + fn name(&self) -> &'static str { + "to_json" + } + + fn run(&self, arguments: &[Value], _context: &Map) -> Result { + Error::expect_built_in_function_argument_amount(self, 1, arguments.len())?; + + let value = arguments.first().unwrap(); + let json_string = serde_json::to_string(&value)?; + + Ok(Value::String(json_string)) + } +} diff --git a/src/built_in_functions/mod.rs b/src/built_in_functions/mod.rs index ae50ff0..7f968a6 100644 --- a/src/built_in_functions/mod.rs +++ b/src/built_in_functions/mod.rs @@ -1,13 +1,16 @@ use crate::{Map, Result, Value}; mod assert; +mod data_formats; mod fs; mod output; mod r#type; -pub const BUILT_IN_FUNCTIONS: [&dyn BuiltInFunction; 7] = [ +pub const BUILT_IN_FUNCTIONS: [&dyn BuiltInFunction; 9] = [ &assert::Assert, &assert::AssertEqual, + &data_formats::FromJson, + &data_formats::ToJson, &fs::Read, &fs::Write, &fs::Append,