expression

Stream one JSON object per output line

JSON Lines is a record-oriented output convention: each line is a separate compact JSON value. A serializer handles embedded newlines by escaping them. Do not mix diagnostics into this stream. It is not a single JSON array. Fixture: Expected stdout (not executed): {"id":1,"name":"oak"} {"id":2,"name":"a\nb"} Expected stderr: (empty) Expected exit: 0 Common mistake: Pretty-printing a multi-line object or constructing JSON with string interpolation.

Formal Syntax & Structure

rust syntaxrust
serde_json::to_writer(&mut out, &record)?

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    use std::io::{self, Write};    #[derive(serde::Serialize)]    struct Row<'a> { id: u32, name: &'a str }    let mut out = io::BufWriter::new(io::stdout().lock());    for row in [Row { id: 1, name: "oak" }, Row { id: 2, name: "a\nb" }] {        serde_json::to_writer(&mut out, &row)?;        out.write_all(b"\n")?;    }    out.flush()?;    Ok(())}
Rust Reference