use serde_json::ser::Formatter;
#[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"]}"#
);
}
}