Istvan
Istvan

Reputation: 8562

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?

Upvotes: 13

Views: 5196

Answers (2)

Joel M
Joel M

Reputation: 381

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))

Upvotes: 10

KobbyPemson
KobbyPemson

Reputation: 2539

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 ]
;;   }
;; }

Upvotes: 10

Related Questions