libjsonutils/
print.rs

1//! Pretty-printing JSONs with ease.
2
3use serde::Serialize;
4use serde_json::{ser::PrettyFormatter, Serializer};
5
6use crate::error::Error;
7
8/// Pretty-print a serializable value as JSON with a default indentation of 4 spaces.
9/// Will returns an [Error] if the value cannot be serialized or if the output is not valid UTF-8.
10///
11/// ```rust
12/// use jsonutils::print::print_json;
13/// use serde_json::json;
14///
15/// let json = json!({
16///    "name": "Alice",
17///    "age": 30,
18///    "is_student": false
19/// });
20///
21/// print_json(json).unwrap();
22/// ```
23
24pub fn print_json<T: Serialize>(value: T) -> Result<(), Error> {
25    let mut buf = Vec::new();
26    let fmtr = PrettyFormatter::with_indent(b"    ");
27    let mut ser = Serializer::with_formatter(&mut buf, fmtr);
28
29    value.serialize(&mut ser).map_err(Error::json)?;
30    println!("{}", String::from_utf8(buf).map_err(Error::utf8)?);
31    Ok(())
32}
33
34/// Pretty-print a serializable value as JSON with a custom indentation.
35/// Will returns an [Error] if the value cannot be serialized or if the output is not valid UTF-8.
36/// 
37/// ```rust
38/// use jsonutils::print::print_json_with_indent;
39/// use serde_json::json;
40///
41/// let json = json!({
42///    "name": "Alice",
43///    "age": 30,
44///    "is_student": false
45/// });
46///
47/// print_json_with_indent(json, 2).unwrap();
48/// ```
49
50pub fn print_json_with_indent<T: Serialize>(value: T, indent: usize) -> Result<(), Error> {
51    let indent = " ".repeat(indent);
52    let indent = indent.as_bytes();
53    let mut buf = Vec::new();
54    let fmtr = PrettyFormatter::with_indent(indent);
55    let mut ser = Serializer::with_formatter(&mut buf, fmtr);
56
57    value.serialize(&mut ser).map_err(Error::json)?;
58    println!("{}", String::from_utf8(buf).map_err(Error::utf8)?);
59    Ok(())
60}