Generate pretty (indented) JSON with serde

我是研究僧i 提交于 2019-12-03 23:20:37

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

#[macro_use]
extern crate serde_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.

#[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());
}

Use the to_string_pretty function to get indented JSON:

::serde_json::to_string_pretty(&obj)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!