Created
May 8, 2025 17:41
-
-
Save momvart/0c3cbb8b5e1bfbf203e19df17638d9e1 to your computer and use it in GitHub Desktop.
A JSON Lines formatter for Rust `serde_json` #jsonl #rust #serde
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Default)] | |
pub(crate) struct JsonLinesFormatter { | |
depth: usize, | |
} | |
use serde_json::ser::{CompactFormatter, Formatter as JsonFormatter}; | |
impl JsonFormatter for JsonLinesFormatter { | |
fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()> | |
where | |
W: ?Sized + io::Write, | |
{ | |
self.depth += 1; | |
CompactFormatter.begin_object(writer) | |
} | |
fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()> | |
where | |
W: ?Sized + io::Write, | |
{ | |
self.depth -= 1; | |
CompactFormatter.end_object(writer).and_then(|_| { | |
if self.depth == 0 { | |
writer.write(&[b'\n']).map(|_| ()) | |
} else { | |
Ok(()) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment