Skip to main content

netpulse/export/
json.rs

1// src/export/json.rs — JSON Streaming Exporter
2//
3// Writes StatsSnapshot entries as newline-delimited JSON (NDJSON) to stdout.
4// This format is ideal for piping into tools like `jq`, `grep`, logging
5// aggregators, or any streaming JSON consumer.
6//
7// Example output line:
8// {"target":"8.8.8.8","sample_count":60,"loss_pct":0.0,"rtt_p50_us":12340,...}
9
10use crate::stats::StatsSnapshot;
11use anyhow::Result;
12use std::io::{self, Write};
13
14/// Exporter that writes StatsSnapshots as NDJSON to stdout.
15pub struct JsonExporter {
16    /// If true, emit each individual ProbeResult in addition to summaries.
17    /// Use for real-time streaming; disable for periodic summary mode.
18    pretty: bool,
19}
20
21impl JsonExporter {
22    pub fn new(pretty: bool) -> Self {
23        Self { pretty }
24    }
25
26    /// Write a single StatsSnapshot as one JSON line to stdout.
27    pub fn emit(&self, snapshot: &StatsSnapshot) -> Result<()> {
28        let stdout = io::stdout();
29        let mut handle = stdout.lock();
30
31        let json = if self.pretty {
32            serde_json::to_string_pretty(snapshot)?
33        } else {
34            serde_json::to_string(snapshot)?
35        };
36
37        writeln!(handle, "{}", json)?;
38        handle.flush()?;
39        Ok(())
40    }
41}