1

I want to pretty print some JSON using the serde crate for Rust. Using serde_json::to_string I can get this:

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

If I switch to serde_json::to_string_pretty I get this:

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

However, I want something inbetween with spaces to make it easier on the eye, but no linebreak so it stays on one row:

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

How can I achieve this? Note that the actual JSON being stringified might be more complex containing unkown levels of nesting. So just pretty printing and then stripping out the line breaks will not work.

Anders
  • 8,307
  • 9
  • 56
  • 88
  • Related to this question: https://stackoverflow.com/questions/42722169/generate-pretty-indented-json-with-serde/49087292#49087292 – Anders Aug 02 '19 at 13:38

1 Answers1

3

Under the hood, to_string_pretty calls Serializer::with_formatter, using the built-in PrettyFormatter.

Your options are either:

  • Create a custom implementation of Formatter to output the JSON in the format you want. Copying and pasting PrettyFormatter would probably be a good start!
  • Amend PrettyFormatter to offer this as an option and submit a pull request. It already allows you to customize the string used for indenting, so I don't think allowing the removal of new-lines would be much of a stretch!
Joe Clay
  • 33,401
  • 4
  • 85
  • 85