askama/filters/
json.rs

1use crate::error::{Error, Result};
2use askama_escape::JsonEscapeBuffer;
3use serde::Serialize;
4use serde_json::to_writer_pretty;
5
6/// Serialize to JSON (requires `json` feature)
7///
8/// The generated string does not contain ampersands `&`, chevrons `< >`, or apostrophes `'`.
9/// To use it in a `<script>` you can combine it with the safe filter:
10///
11/// ``` html
12/// <script>
13/// var data = {{data|json|safe}};
14/// </script>
15/// ```
16///
17/// To use it in HTML attributes, you can either use it in quotation marks `"{{data|json}}"` as is,
18/// or in apostrophes with the (optional) safe filter `'{{data|json|safe}}'`.
19/// In HTML texts the output of e.g. `<pre>{{data|json|safe}}</pre>` is safe, too.
20pub fn json<S: Serialize>(s: S) -> Result<String> {
21    let mut writer = JsonEscapeBuffer::new();
22    to_writer_pretty(&mut writer, &s).map_err(Error::from)?;
23    Ok(writer.finish())
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn test_json() {
32        assert_eq!(json(true).unwrap(), "true");
33        assert_eq!(json("foo").unwrap(), r#""foo""#);
34        assert_eq!(json(true).unwrap(), "true");
35        assert_eq!(json("foo").unwrap(), r#""foo""#);
36        assert_eq!(
37            json(vec!["foo", "bar"]).unwrap(),
38            r#"[
39  "foo",
40  "bar"
41]"#
42        );
43    }
44}