use serde_json::Value;
use flowcore::errors::Result;
use flowcore::{RunAgain, RUN_AGAIN};
use flowmacro::flow_function;
#[flow_function]
fn inner_to_json(input: &str) -> Result<(Option<Value>, RunAgain)> {
match serde_json::from_str(input) {
Ok(json) => Ok((Some(json), RUN_AGAIN)),
Err(_) => Ok((
Some(serde_json::Value::String(input.to_string())),
RUN_AGAIN,
)),
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod test {
use std::collections::HashMap;
use serde_json::{json, Value};
use super::inner_to_json;
fn test_to_json(string: &str, expected_value: &Value) {
let (result, _) = inner_to_json(string).expect("_to_json() failed");
match result {
Some(value) => {
assert_eq!(&value, expected_value);
}
None => panic!("No Result returned"),
}
}
#[test]
fn parse_string() {
test_to_json("\"Hello World\"", &json!("Hello World"));
}
#[test]
fn parse_number() {
test_to_json("42", &json!(42));
}
#[test]
fn parse_null() {
test_to_json("null", &serde_json::Value::Null);
}
#[test]
fn parse_array() {
test_to_json("[1,2,3,4]", &json!([1, 2, 3, 4]));
}
#[test]
fn parse_invalid() {
test_to_json("-1.20,0.35", &json!("-1.20,0.35"));
}
#[test]
fn parse_map() {
let mut map: HashMap<&str, u32> = HashMap::new();
map.insert("Meaning", 42);
map.insert("Size", 9);
test_to_json("{\"Meaning\":42,\"Size\":9}", &json!(map));
}
}