Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty print JSON to a file in Clojure?

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?

like image 344
Istvan Avatar asked Apr 26 '14 06:04

Istvan


People also ask

Is there a JSON parser for Clojure?

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.

What is pretty printing in JSON?

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.

How to pretty print JSON file on Ubuntu display?

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.

How to minify a JSON file in Python?

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.


2 Answers

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 ]
;;   }
;; }
like image 168
KobbyPemson Avatar answered Sep 28 '22 04:09

KobbyPemson


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))
like image 26
Joel M Avatar answered Sep 28 '22 03:09

Joel M