Json Beautifier

Is there a way to "beautify" or format a json string in racket?
E.g. from

{ "name":"She-Ra","title":"The Princess of Power"}

to

{
  "name": "She-Ra",
  "title": "The Princess of Power"
}

?

Not yet, but there's an open PR!

1 Like

My SwDev package (organically grown, undocument at this point) at https://github.com/mfelleisen/SwDev contains a module for pretty printing JSON:

https://github.com/mfelleisen/SwDev/blob/master/Lib/json-pretty.rkt

It’s a WIP, started by Tony Garnock-Jones.

1 Like

How much do you want the output to look "beautiful"?

Most JSON beautification uses a pretty printer to print the output in a way that doesn't exceed the width limit and looks nice. The proposed changes to write-json in the PR that @LiberalArtist referred to, on the other hand, employs some ad-hoc heuristics to make it look nicer than printing everything in one line, but the output is almost certainly going to be inferior to the pretty printing approach (though its advantage is that it will be faster to print).

I'm not aware of a package in Racket that does JSON beautification via pretty printing. However, there are packages that provide pretty printing functionality. https://docs.racket-lang.org/pprint/, for instance, would be suitable for pretty printing JSON.

1 Like

I don't think I've seen a standard-library function that does JSON "pretty printing" in the sense you mention of being sensitive to the target width. The functions I've surveyed don't use a heuristic, either: they uniformly start a new line with some indentation for each array element or object key–value pair. I see now that https://github.com/racket/racket/pull/4300 does currently use an ad-hoc heuristic: I've just commented there to say that I don't think it should.

The racket/pretty library is another option for building that sort of thing.

1 Like

Thank you, I will try "racket/pretty" until the mr is merged

In the argo JSON package, there's a pretty-print function (there's even a raco command!), but it's just a wrapper around racket/pretty, nothing fancy like what @sorawee has in mind. Looking forward to seeing that PR merged in!

Since the JSON library is a single file, you could also grab the version from the PR for now and change (require "json.rkt") to (require json) once it's merged.