Skip to main content

plf_contrib/
json.rs

1use plf::{Kwargs, State, TeraResult, Value};
2
3/// Encodes a value as JSON.
4/// Takes an optional `pretty` boolean argument defaulting to false.
5///
6/// ```text
7/// {{ value | json_encode }}
8/// {{ value | json_encode(pretty=true) }}
9/// ```
10pub fn json_encode(val: &Value, kwargs: Kwargs, _: &State) -> TeraResult<String> {
11    let pretty = kwargs.get::<bool>("pretty")?.unwrap_or(false);
12    let res = if pretty {
13        serde_json::to_string_pretty(val)
14    } else {
15        serde_json::to_string(val)
16    };
17    res.map_err(|e| plf::Error::message(format!("Error encoding to JSON: {e}")))
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23    use std::sync::Arc;
24    use plf::value::Map;
25    use plf::{Context, Kwargs, State, Value};
26
27    #[test]
28    fn test_json_encode() {
29        let ctx = Context::new();
30        let state = State::new(&ctx);
31        let mut obj = Map::new();
32        obj.insert("a".into(), Value::from(1));
33        let val = Value::from(obj);
34        assert_eq!(
35            json_encode(&val, Kwargs::default(), &state).unwrap(),
36            r#"{"a":1}"#
37        );
38    }
39
40    #[test]
41    fn test_json_encode_pretty() {
42        let ctx = Context::new();
43        let state = State::new(&ctx);
44        let mut kwargs_map = Map::new();
45        kwargs_map.insert("pretty".into(), true.into());
46        let kwargs = Kwargs::new(Arc::new(kwargs_map));
47        let mut obj = Map::new();
48        obj.insert("a".into(), Value::from(1));
49        let val = Value::from(obj);
50        assert_eq!(
51            json_encode(&val, kwargs, &state).unwrap(),
52            "{\n  \"a\": 1\n}"
53        );
54    }
55
56    #[test]
57    fn test_register() {
58        let mut tera = plf::Tera::default();
59        tera.register_filter("json_encode", json_encode);
60    }
61}