From 99dd189328afce51f38ca705ec9be64b9869055f Mon Sep 17 00:00:00 2001 From: Jeff Date: Thu, 30 Nov 2023 10:10:03 -0500 Subject: [PATCH] Implement from_json and to_json --- src/built_in_functions/data_formats.rs | 35 ++++++++++++++++++++++++++ src/built_in_functions/mod.rs | 5 +++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/built_in_functions/data_formats.rs 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,