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

Format json structs #21330

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

jonasdiemer
Copy link

@jonasdiemer jonasdiemer commented Sep 7, 2024

Hi,

this is a prototype to simplify formatting/printing of structs that contain strings (which fall back to list of characters using the default formatter). It uses the specifier 'j' to json.stringify the struct.

Please consider this a "request for comment" - is this a good idea? Alternatively, maybe enable use of 's' specifier to format structs as ZON (with "proper" handling of strings)?

The rationale is that I think it's rather common to debug.print structs that contain strings (e.g. HTTP responses), and the default behavior with strings as character lists is clumsy.

Looking forward to comments.

@rohlem
Copy link
Contributor

rohlem commented Sep 7, 2024

I believe the formatter function std.json.fmt already exists exactly for this purpose.
It takes any argument and wraps it with an std.fmt.Formatter specialization that provides an appropriate format method.
Current usage example: std.log.warn("{}", .{std.json.fmt(.{.a = "asdf", .x = 30}, .{})}).

@jonasdiemer
Copy link
Author

Thanks, for some reason I only found json.stringify (which needs a writer).

Still, for the proposal feels more convenient:

std.debug.print("json: {}\n", .{std.json.fmt(x, .{})});

vs

std.debug.print("struct: {j}\n", .{x});

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

Successfully merging this pull request may close these issues.

2 participants