rustserde

Can serde_json::to_writer_pretty indent with tabs rather than 2 spaces?


Can serde_json::to_writer_pretty indent with tabs rather than 2 spaces?

    let file = std::fs::File::create(&path).expect("Failed to create json file");
    let mut w = BufWriter::new(file);
    serde_json::to_writer_pretty(&mut w, &data).expect("Failed to write to json file");

How do I tell serde_json::to_writer_pretty to use tabs, or is there some other way?

I have a different tool generating JSON with tabs, so I want to use tabs to diff the files.


Solution

  • You would need to use PrettyFormatter::with_indent and Serializer::with_formatter.

    let tabs_pretty = serde_json::ser::PrettyFormatter::with_indent(b"\t");
    let mut ser = serde_json::Serializer::with_formatter(&mut w, tabs_pretty);
    serde::Serialize::serialize(&data, &mut ser).expect("Failed to write to json file");