使用 serde 生成漂亮(缩进)JSON

Generate pretty (indented) JSON with serde

使用 serde_json 箱子,我可以使用

::serde_json::to_string(&obj)

将对象序列化为 JSON 字符串。结果 JSON 使用紧凑格式,例如:

{"foo":1,"bar":2}

但是如何生成pretty/indentedJSON?例如,我想得到这个:

{
  "foo": 1,
  "bar": 2
}

使用 to_string_pretty 函数进行缩进 JSON:

::serde_json::to_string_pretty(&obj)

serde_json::to_string_pretty 函数生成 pretty-printed 缩进 JSON。

#[macro_use]
extern crate serde_json;

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

此方法默认缩进 2 个空格,这恰好是您在问题中要求的。您可以使用 PrettyFormatter::with_indent.

自定义缩进
#[macro_use]
extern crate serde_json;

extern crate serde;
use serde::Serialize;

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

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