Create beautiful (indented) JSON with a heart

Using serde_json , I can use

::serde_json::to_string(&obj) 

to serialize the object into a JSON string. As a result, JSON uses compact formatting, for example:

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

But how do I create cute / indented JSON? For example, I would like to get the following:

 { "foo": 1, "bar": 2 } 
+6
source share
2 answers

Use the to_string_pretty function to get JSON indents:

 ::serde_json::to_string_pretty(&obj) 
+6
source

The serde_json::to_string_pretty generates fairly imprinted JSON indents.

 #[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 by default has two spaces in the indentation, which, as it turns out, are what you asked in your question. You can indent 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()); } 
0
source

Source: https://habr.com/ru/post/1015658/


All Articles