Skip to content

Convenience functions for working with Formatter / PrettyFormatter #1319

@tgross35

Description

@tgross35

As far as I can tell, using a custom formatter requires interfacing with Serializer, which means any crate doing this needs the direct serde_core dependency:

use serde_core::Serialize;
use serde_json::{Serializer, json, ser::PrettyFormatter};

fn main() {
    let j = json! {{"a": [1, 2, 3], "b": {}}};
    let p = PrettyFormatter::with_indent(b"    ");
    let mut v = Vec::new();
    let mut s = Serializer::with_formatter(&mut v, p);
    j.serialize(&mut s).unwrap();
    println!("{}", str::from_utf8(&v).unwrap());
}

Would it be possible to add convenience functions like to_{string,vec,writer}_formatter that make this easier?

pub fn to_string_formatter<T, F>(value: &T, formatter: F) -> Result<String>
where
    T: ?Sized + Serialize,
    F: Formatter;
fn main() {
    let j = json! {{"a": [1, 2, 3], "b": {}}};
    let p = PrettyFormatter::with_indent(b"    ");
    println!("{}", serde::to_string_formatter(&j, p).unwrap());
}

Any -> String versions should emit an error if the indentation is not valid UTF-8 (#750).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions