I would like to store JSON content in files but using the pretty version.
Just to be clear, this is the normal JSON:
{"b":2, "a":1}
This is the pretty version of it:
{
"b": 2,
"a": 1
}
Is there a way in Clojure to achieve this?
JSON parser/generator to/from Clojure data structures. This project follows the version scheme MAJOR.MINOR.PATCH where each component provides some relative indication of the size of the change, but does not follow semantic versioning.
When you get a JSON file or down some JSON from an API, it will usually be in a minified version in order to save bandwidth. But, for reading the JSON or for debugging, it can often be easier to print out the JSON in a more structured format. Pretty printing means having proper line breaks, indentation, white space, and overall structure.
With universe repository enabled, you can install it on Ubuntu using the apt command: Once you have it installed, use it in the following manner to pretty print JSON file on the display: You may also tempt to use cat but I believe it one of the useless use of cat command. Keep in mind that the above command will not impact the original JSON file.
Let’s take a reverse stance and minify a well formatted JSON file. To minify a JSON file, you can use the compact option -c. It’s more likely that you have Python installed on your system. If that’s the case, you can use it pretty print the JSON file in the terminal: I know there are other ways to parse JSON file and print it with proper format.
Use the cheshire library found here and use the generate-string function with the pretty flag set to true
Example
;; generate some JSON with pretty formatting
(generate-string {:foo "bar" :baz {:eggplant [1 2 3]}} {:pretty true})
;; {
;; "foo" : "bar",
;; "baz" : {
;; "eggplant" : [ 1, 2, 3 ]
;; }
;; }
You can use the built-in with-out-str
function to capture anything written to the output buffer and store it as a string.
(with-out-str (clojure.data.json/pprint your-map-or-whatever))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With