1use crate::error::{Error, Result};
2use askama_escape::JsonEscapeBuffer;
3use serde::Serialize;
4use serde_json::to_writer_pretty;
56/// 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> {
21let mut writer = JsonEscapeBuffer::new();
22 to_writer_pretty(&mut writer, &s).map_err(Error::from)?;
23Ok(writer.finish())
24}
2526#[cfg(test)]
27mod tests {
28use super::*;
2930#[test]
31fn test_json() {
32assert_eq!(json(true).unwrap(), "true");
33assert_eq!(json("foo").unwrap(), r#""foo""#);
34assert_eq!(json(true).unwrap(), "true");
35assert_eq!(json("foo").unwrap(), r#""foo""#);
36assert_eq!(
37 json(vec!["foo", "bar"]).unwrap(),
38r#"[
39 "foo",
40 "bar"
41]"#
42);
43 }
44}