HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

Generate pretty (indented) JSON with serde

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withindentedprettyserdegeneratejson

Problem

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
}

Solution

The serde_json::to_string_pretty function generates pretty-printed indented JSON.

use serde_json::json;

fn main() {
    let obj = json!({"foo":1,"bar":2});
    println!("{}", serde_json::to_string_pretty(&obj).unwrap());
}


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.

use serde::Serialize;
use serde_json::json;

fn main() {
    let obj = json!({"foo":1,"bar":2});

    let mut buf = Vec::new();
    let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
    let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
    obj.serialize(&mut ser).unwrap();
    println!("{}", String::from_utf8(buf).unwrap());
}

Code Snippets

use serde_json::json;

fn main() {
    let obj = json!({"foo":1,"bar":2});
    println!("{}", serde_json::to_string_pretty(&obj).unwrap());
}
use serde::Serialize;
use serde_json::json;

fn main() {
    let obj = json!({"foo":1,"bar":2});

    let mut buf = Vec::new();
    let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
    let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
    obj.serialize(&mut ser).unwrap();
    println!("{}", String::from_utf8(buf).unwrap());
}

Context

Stack Overflow Q#42722169, score: 117

Revisions (0)

No revisions yet.