serde_json_python_formatter/
lib.rs

1//! Provides a [`serde_json::ser::Formatter`] that mimics the output of Pythons `json.dumps()`.
2
3use serde_json::ser::Formatter;
4
5/// A [`serde_json::ser::Formatter`] that mimics the output of Pythons `json.dumps`.
6///
7/// # Example
8///
9/// ```rust
10/// # use serde_json::json;
11/// # use serde::ser::Serialize;
12/// # use serde_json_python_formatter::PythonFormatter;
13/// let mut buf = Vec::new();
14/// let mut serializer = serde_json::Serializer::with_formatter(&mut buf, PythonFormatter::default());
15/// json!({"hello":"world"}).serialize(&mut serializer).unwrap();
16/// let json_string = String::from_utf8(buf).unwrap();
17/// ```
18#[derive(Clone, Debug, Default)]
19pub struct PythonFormatter {}
20
21impl Formatter for PythonFormatter {
22    #[inline]
23    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> std::io::Result<()>
24    where
25        W: ?Sized + std::io::Write,
26    {
27        if first {
28            Ok(())
29        } else {
30            writer.write_all(b", ")
31        }
32    }
33
34    #[inline]
35    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> std::io::Result<()>
36    where
37        W: ?Sized + std::io::Write,
38    {
39        if first {
40            Ok(())
41        } else {
42            writer.write_all(b", ")
43        }
44    }
45
46    #[inline]
47    fn begin_object_value<W>(&mut self, writer: &mut W) -> std::io::Result<()>
48    where
49        W: ?Sized + std::io::Write,
50    {
51        writer.write_all(b": ")
52    }
53}
54
55#[cfg(test)]
56mod test {
57    use super::PythonFormatter;
58    use serde::ser::Serialize;
59    use serde_json::json;
60
61    #[test]
62    pub fn test_output() {
63        let json = json!({
64            "foo": "bar",
65            "hello": ["world"],
66            "dirk": {
67                "sub": 3.14
68            }
69        });
70
71        let mut buf = Vec::new();
72        let mut serializer =
73            serde_json::Serializer::with_formatter(&mut buf, PythonFormatter::default());
74        json.serialize(&mut serializer).unwrap();
75        let json = String::from_utf8(buf).unwrap();
76
77        assert_eq!(
78            &json,
79            r#"{"dirk": {"sub": 3.14}, "foo": "bar", "hello": ["world"]}"#
80        );
81    }
82}