使用serde生成漂亮的(缩进的)JSON [英] Generate pretty (indented) JSON with serde

查看:164
本文介绍了使用serde生成漂亮的(缩进的)JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 serde_json 板条箱,我可以使用

Using the serde_json crate, I can use

::serde_json::to_string(&obj)

将对象序列化为JSON字符串.生成的JSON使用紧凑格式,例如:

to serialize an object into a JSON string. The resulting JSON uses compact formatting, like:

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

但是如何生成漂亮的/缩进的JSON?例如,我想得到这个:

But how do I generate pretty/indented JSON? For example, I'd like to get this:

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

推荐答案

serde_json::to_string_pretty 函数生成精美打印的缩进JSON.

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

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

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

这篇关于使用serde生成漂亮的(缩进的)JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆