Using the serde_json crate, I can use
::serde_json::to_string(&obj)
to serialize an object into a JSON string. The resulting JSON uses compact formatting, like:
{"foo":1,"bar":2}
But how do I generate pretty/indented JSON? For example, I'd like to get this:
{
"foo": 1,
"bar": 2
}
Use the
to_string_pretty
function to get indented JSON:The
serde_json::to_string_pretty
function generates pretty-printed indented JSON.This approach defaults to 2 spaces of indentation, which happens to be what you asked for in your question. You can customize the indentation by using
PrettyFormatter::with_indent
.