Chức năng serde_json::to_string_pretty
tạo ra khá-in JSON thụt vào.
#[macro_use]
extern crate serde_json;
fn main() {
let obj = json!({"foo":1,"bar":2});
println!("{}", serde_json::to_string_pretty(&obj).unwrap());
}
Cách tiếp cận này mặc định là 2 khoảng trống thụt đầu dòng, điều này xảy ra với những gì bạn hỏi trong câu hỏi của bạn. Bạn có thể tùy chỉnh thụt đầu dòng bằng cách sử dụng 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());
}
Có cách nào để đặt thụt lề không? Theo mặc định, có vẻ như 2 dấu cách. – pietrovismara