1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use crate::error::{Error, Result};
use askama_escape::JsonEscapeBuffer;
use serde::Serialize;
use serde_json::to_writer_pretty;

/// Serialize to JSON (requires `json` feature)
///
/// The generated string does not contain ampersands `&`, chevrons `< >`, or apostrophes `'`.
/// To use it in a `<script>` you can combine it with the safe filter:
///
/// ``` html
/// <script>
/// var data = {{data|json|safe}};
/// </script>
/// ```
///
/// To use it in HTML attributes, you can either use it in quotation marks `"{{data|json}}"` as is,
/// or in apostrophes with the (optional) safe filter `'{{data|json|safe}}'`.
/// In HTML texts the output of e.g. `<pre>{{data|json|safe}}</pre>` is safe, too.
pub fn json<S: Serialize>(s: S) -> Result<String> {
    let mut writer = JsonEscapeBuffer::new();
    to_writer_pretty(&mut writer, &s).map_err(Error::from)?;
    Ok(writer.finish())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json() {
        assert_eq!(json(true).unwrap(), "true");
        assert_eq!(json("foo").unwrap(), r#""foo""#);
        assert_eq!(json(&true).unwrap(), "true");
        assert_eq!(json(&"foo").unwrap(), r#""foo""#);
        assert_eq!(
            json(&vec!["foo", "bar"]).unwrap(),
            r#"[
  "foo",
  "bar"
]"#
        );
    }
}