Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pretty print indent #1002

Closed
wants to merge 2 commits into from
Closed

Conversation

jwpjrdev
Copy link

currently, if a user of the library wants to serialise to a pretty JSON string with an indent other than 2 spaces, this is the way to go about it:

let value = ...;

let mut buf = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
value.serialize(&mut ser)?;
let pretty_json = String::from_utf8(buf)?;

not fun.

this PR adds a couple methods, culminating in serde_json::to_string_pretty_indent. it does the exact same thing as to_string_pretty but it allows you to pass an indent such as b" " down the chain to PrettyFormatter. this can be used like so:

let value = ...;

let pretty_json = serde_json::to_string_pretty_indent(&json, b"    ")?;

i have not written any tests because i poked around and saw that there were a lot of things going on. some help with that would be greatly appreciated. i already tested the additions in another project of mine to ensure that it does function.

@jwpjrdev
Copy link
Author

i'm also curious—why must a &[u8] be provided? wouldn't a usize be better?

that way, instead of providing b" ", you could just provide 4. i continued that trend in this PR but i feel like it might be useful to add another method alongside to_string_pretty_indent that simply uses usize because that's what 99% of people will be using.

Copy link
Member

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think indenting with non-2 indentation is uncommon enough that it won't make sense to dedicate 3 whole new top-level functions to this use case. Using PrettyFormatter::with_indent / Serializer::with_formatter as you showed is what I would recommend, or you can wrap the same thing in a helper function if it's needed frequently in a particular project.

Thanks anyway for the PR!

@dtolnay dtolnay closed this Mar 20, 2023
@jwpjrdev
Copy link
Author

thank you! i'm still rather confused about why it accepts &[u8] rather than a usize, though.

@dtolnay
Copy link
Member

dtolnay commented Mar 20, 2023

Non-space indents? b"\t"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants