serde-json-python-formatter 0.1.0

A serde-json formatter to mimic Python output
Documentation
//! Provides a [`serde_json::ser::Formatter`] that mimics the output of Pythons `json.dumps()`.

use serde_json::ser::Formatter;

/// A [`serde_json::ser::Formatter`] that mimics the output of Pythons `json.dumps`.
///
/// # Example
///
/// ```rust
/// # use serde_json::json;
/// # use serde::ser::Serialize;
/// # use serde_json_python_formatter::PythonFormatter;
/// let mut buf = Vec::new();
/// let mut serializer = serde_json::Serializer::with_formatter(&mut buf, PythonFormatter::default());
/// json!({"hello":"world"}).serialize(&mut serializer).unwrap();
/// let json_string = String::from_utf8(buf).unwrap();
/// ```
#[derive(Clone, Debug, Default)]
pub struct PythonFormatter {}

impl Formatter for PythonFormatter {
    #[inline]
    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> std::io::Result<()>
    where
        W: ?Sized + std::io::Write,
    {
        if first {
            Ok(())
        } else {
            writer.write_all(b", ")
        }
    }

    #[inline]
    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> std::io::Result<()>
    where
        W: ?Sized + std::io::Write,
    {
        if first {
            Ok(())
        } else {
            writer.write_all(b", ")
        }
    }

    #[inline]
    fn begin_object_value<W>(&mut self, writer: &mut W) -> std::io::Result<()>
    where
        W: ?Sized + std::io::Write,
    {
        writer.write_all(b": ")
    }
}

#[cfg(test)]
mod test {
    use super::PythonFormatter;
    use serde::ser::Serialize;
    use serde_json::json;

    #[test]
    pub fn test_output() {
        let json = json!({
            "foo": "bar",
            "hello": ["world"],
            "dirk": {
                "sub": 3.14
            }
        });

        let mut buf = Vec::new();
        let mut serializer =
            serde_json::Serializer::with_formatter(&mut buf, PythonFormatter::default());
        json.serialize(&mut serializer).unwrap();
        let json = String::from_utf8(buf).unwrap();

        assert_eq!(
            &json,
            r#"{"dirk": {"sub": 3.14}, "foo": "bar", "hello": ["world"]}"#
        );
    }
}