Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate pretty (indented) JSON with serde

Tags:

json

rust

serde

Using the serde_json crate, I can use

::serde_json::to_string(&obj) 

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

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

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

{   "foo": 1,   "bar": 2 } 
like image 816
Jo Liss Avatar asked Mar 10 '17 15:03

Jo Liss


People also ask

How do I make JSON data pretty?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

What is Serde JSON?

Serde JSON JSON is a ubiquitous open-standard format that uses human-readable text to transmit data objects consisting of key-value pairs. { "name": "John Doe", "age": 43, "address": { "street": "10 Downing Street", "city": "London" }, "phones": [ "+44 1234567", "+44 2345678" ] }

What is JSON pretty format?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .

What is JSON AWS?

JavaScript Object Notation, more commonly known by the acronym JSON, is an open data interchange format that is both human and machine-readable. Despite the name JavaScript Object Notation, JSON is independent of any programming language and is a common API output in a wide variety of applications.


1 Answers

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()); } 
like image 56
dtolnay Avatar answered Sep 21 '22 05:09

dtolnay